babylon.max.js 3.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849
  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.data = new Array(capacity);
  5617. this._id = SmartArray._GlobalId++;
  5618. }
  5619. SmartArray.prototype.push = function (value) {
  5620. this.data[this.length++] = value;
  5621. if (this.length > this.data.length) {
  5622. this.data.length *= 2;
  5623. }
  5624. };
  5625. SmartArray.prototype.forEach = function (func) {
  5626. for (var index = 0; index < this.length; index++) {
  5627. func(this.data[index]);
  5628. }
  5629. };
  5630. SmartArray.prototype.sort = function (compareFn) {
  5631. this.data.sort(compareFn);
  5632. };
  5633. SmartArray.prototype.reset = function () {
  5634. this.length = 0;
  5635. };
  5636. SmartArray.prototype.dispose = function () {
  5637. this.reset();
  5638. if (this.data) {
  5639. this.data.length = 0;
  5640. this.data = [];
  5641. }
  5642. };
  5643. SmartArray.prototype.concat = function (array) {
  5644. if (array.length === 0) {
  5645. return;
  5646. }
  5647. if (this.length + array.length > this.data.length) {
  5648. this.data.length = (this.length + array.length) * 2;
  5649. }
  5650. for (var index = 0; index < array.length; index++) {
  5651. this.data[this.length++] = (array.data || array)[index];
  5652. }
  5653. };
  5654. SmartArray.prototype.indexOf = function (value) {
  5655. var position = this.data.indexOf(value);
  5656. if (position >= this.length) {
  5657. return -1;
  5658. }
  5659. return position;
  5660. };
  5661. SmartArray.prototype.contains = function (value) {
  5662. return this.data.indexOf(value) !== -1;
  5663. };
  5664. // Statics
  5665. SmartArray._GlobalId = 0;
  5666. return SmartArray;
  5667. }());
  5668. BABYLON.SmartArray = SmartArray;
  5669. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5670. __extends(SmartArrayNoDuplicate, _super);
  5671. function SmartArrayNoDuplicate() {
  5672. var _this = _super !== null && _super.apply(this, arguments) || this;
  5673. _this._duplicateId = 0;
  5674. return _this;
  5675. }
  5676. SmartArrayNoDuplicate.prototype.push = function (value) {
  5677. _super.prototype.push.call(this, value);
  5678. if (!value.__smartArrayFlags) {
  5679. value.__smartArrayFlags = {};
  5680. }
  5681. value.__smartArrayFlags[this._id] = this._duplicateId;
  5682. };
  5683. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5684. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5685. return false;
  5686. }
  5687. this.push(value);
  5688. return true;
  5689. };
  5690. SmartArrayNoDuplicate.prototype.reset = function () {
  5691. _super.prototype.reset.call(this);
  5692. this._duplicateId++;
  5693. };
  5694. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5695. if (array.length === 0) {
  5696. return;
  5697. }
  5698. if (this.length + array.length > this.data.length) {
  5699. this.data.length = (this.length + array.length) * 2;
  5700. }
  5701. for (var index = 0; index < array.length; index++) {
  5702. var item = (array.data || array)[index];
  5703. this.pushNoDuplicate(item);
  5704. }
  5705. };
  5706. return SmartArrayNoDuplicate;
  5707. }(SmartArray));
  5708. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5709. })(BABYLON || (BABYLON = {}));
  5710. //# sourceMappingURL=babylon.smartArray.js.map
  5711. var BABYLON;
  5712. (function (BABYLON) {
  5713. // Screenshots
  5714. var screenshotCanvas;
  5715. var cloneValue = function (source, destinationObject) {
  5716. if (!source)
  5717. return null;
  5718. if (source instanceof BABYLON.Mesh) {
  5719. return null;
  5720. }
  5721. if (source instanceof BABYLON.SubMesh) {
  5722. return source.clone(destinationObject);
  5723. }
  5724. else if (source.clone) {
  5725. return source.clone();
  5726. }
  5727. return null;
  5728. };
  5729. var Tools = /** @class */ (function () {
  5730. function Tools() {
  5731. }
  5732. ;
  5733. /**
  5734. * Interpolates between a and b via alpha
  5735. * @param a The lower value (returned when alpha = 0)
  5736. * @param b The upper value (returned when alpha = 1)
  5737. * @param alpha The interpolation-factor
  5738. * @return The mixed value
  5739. */
  5740. Tools.Mix = function (a, b, alpha) {
  5741. return a * (1 - alpha) + b * alpha;
  5742. };
  5743. Tools.Instantiate = function (className) {
  5744. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5745. return Tools.RegisteredExternalClasses[className];
  5746. }
  5747. var arr = className.split(".");
  5748. var fn = (window || this);
  5749. for (var i = 0, len = arr.length; i < len; i++) {
  5750. fn = fn[arr[i]];
  5751. }
  5752. if (typeof fn !== "function") {
  5753. return null;
  5754. }
  5755. return fn;
  5756. };
  5757. Tools.SetImmediate = function (action) {
  5758. if (window.setImmediate) {
  5759. window.setImmediate(action);
  5760. }
  5761. else {
  5762. setTimeout(action, 1);
  5763. }
  5764. };
  5765. Tools.IsExponentOfTwo = function (value) {
  5766. var count = 1;
  5767. do {
  5768. count *= 2;
  5769. } while (count < value);
  5770. return count === value;
  5771. };
  5772. /**
  5773. * Find the next highest power of two.
  5774. * @param x Number to start search from.
  5775. * @return Next highest power of two.
  5776. */
  5777. Tools.CeilingPOT = function (x) {
  5778. x--;
  5779. x |= x >> 1;
  5780. x |= x >> 2;
  5781. x |= x >> 4;
  5782. x |= x >> 8;
  5783. x |= x >> 16;
  5784. x++;
  5785. return x;
  5786. };
  5787. /**
  5788. * Find the next lowest power of two.
  5789. * @param x Number to start search from.
  5790. * @return Next lowest power of two.
  5791. */
  5792. Tools.FloorPOT = function (x) {
  5793. x = x | (x >> 1);
  5794. x = x | (x >> 2);
  5795. x = x | (x >> 4);
  5796. x = x | (x >> 8);
  5797. x = x | (x >> 16);
  5798. return x - (x >> 1);
  5799. };
  5800. /**
  5801. * Find the nearest power of two.
  5802. * @param x Number to start search from.
  5803. * @return Next nearest power of two.
  5804. */
  5805. Tools.NearestPOT = function (x) {
  5806. var c = Tools.CeilingPOT(x);
  5807. var f = Tools.FloorPOT(x);
  5808. return (c - x) > (x - f) ? f : c;
  5809. };
  5810. Tools.GetExponentOfTwo = function (value, max, mode) {
  5811. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5812. var pot;
  5813. switch (mode) {
  5814. case BABYLON.Engine.SCALEMODE_FLOOR:
  5815. pot = Tools.FloorPOT(value);
  5816. break;
  5817. case BABYLON.Engine.SCALEMODE_NEAREST:
  5818. pot = Tools.NearestPOT(value);
  5819. break;
  5820. case BABYLON.Engine.SCALEMODE_CEILING:
  5821. default:
  5822. pot = Tools.CeilingPOT(value);
  5823. break;
  5824. }
  5825. return Math.min(pot, max);
  5826. };
  5827. Tools.GetFilename = function (path) {
  5828. var index = path.lastIndexOf("/");
  5829. if (index < 0)
  5830. return path;
  5831. return path.substring(index + 1);
  5832. };
  5833. Tools.GetDOMTextContent = function (element) {
  5834. var result = "";
  5835. var child = element.firstChild;
  5836. while (child) {
  5837. if (child.nodeType === 3) {
  5838. result += child.textContent;
  5839. }
  5840. child = child.nextSibling;
  5841. }
  5842. return result;
  5843. };
  5844. Tools.ToDegrees = function (angle) {
  5845. return angle * 180 / Math.PI;
  5846. };
  5847. Tools.ToRadians = function (angle) {
  5848. return angle * Math.PI / 180;
  5849. };
  5850. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5851. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5852. var output = "";
  5853. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5854. var i = 0;
  5855. var bytes = new Uint8Array(buffer);
  5856. while (i < bytes.length) {
  5857. chr1 = bytes[i++];
  5858. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5859. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5860. enc1 = chr1 >> 2;
  5861. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5862. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5863. enc4 = chr3 & 63;
  5864. if (isNaN(chr2)) {
  5865. enc3 = enc4 = 64;
  5866. }
  5867. else if (isNaN(chr3)) {
  5868. enc4 = 64;
  5869. }
  5870. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5871. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5872. }
  5873. return "data:image/png;base64," + output;
  5874. };
  5875. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5876. if (bias === void 0) { bias = null; }
  5877. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5878. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5879. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5880. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5881. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5882. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5883. }
  5884. if (bias) {
  5885. minimum.x -= minimum.x * bias.x + bias.y;
  5886. minimum.y -= minimum.y * bias.x + bias.y;
  5887. minimum.z -= minimum.z * bias.x + bias.y;
  5888. maximum.x += maximum.x * bias.x + bias.y;
  5889. maximum.y += maximum.y * bias.x + bias.y;
  5890. maximum.z += maximum.z * bias.x + bias.y;
  5891. }
  5892. return {
  5893. minimum: minimum,
  5894. maximum: maximum
  5895. };
  5896. };
  5897. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5898. if (bias === void 0) { bias = null; }
  5899. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5900. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5901. if (!stride) {
  5902. stride = 3;
  5903. }
  5904. for (var index = start; index < start + count; index++) {
  5905. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5906. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5907. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5908. }
  5909. if (bias) {
  5910. minimum.x -= minimum.x * bias.x + bias.y;
  5911. minimum.y -= minimum.y * bias.x + bias.y;
  5912. minimum.z -= minimum.z * bias.x + bias.y;
  5913. maximum.x += maximum.x * bias.x + bias.y;
  5914. maximum.y += maximum.y * bias.x + bias.y;
  5915. maximum.z += maximum.z * bias.x + bias.y;
  5916. }
  5917. return {
  5918. minimum: minimum,
  5919. maximum: maximum
  5920. };
  5921. };
  5922. Tools.Vector2ArrayFeeder = function (array) {
  5923. return function (index) {
  5924. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5925. var length = isFloatArray ? array.length / 2 : array.length;
  5926. if (index >= length) {
  5927. return null;
  5928. }
  5929. if (isFloatArray) {
  5930. var fa = array;
  5931. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5932. }
  5933. var a = array;
  5934. return a[index];
  5935. };
  5936. };
  5937. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5938. if (bias === void 0) { bias = null; }
  5939. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5940. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5941. var i = 0;
  5942. var cur = feeder(i++);
  5943. while (cur) {
  5944. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5945. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5946. cur = feeder(i++);
  5947. }
  5948. if (bias) {
  5949. minimum.x -= minimum.x * bias.x + bias.y;
  5950. minimum.y -= minimum.y * bias.x + bias.y;
  5951. maximum.x += maximum.x * bias.x + bias.y;
  5952. maximum.y += maximum.y * bias.x + bias.y;
  5953. }
  5954. return {
  5955. minimum: minimum,
  5956. maximum: maximum
  5957. };
  5958. };
  5959. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5960. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5961. return null;
  5962. return Array.isArray(obj) ? obj : [obj];
  5963. };
  5964. // Misc.
  5965. Tools.GetPointerPrefix = function () {
  5966. var eventPrefix = "pointer";
  5967. // Check if pointer events are supported
  5968. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5969. eventPrefix = "mouse";
  5970. }
  5971. return eventPrefix;
  5972. };
  5973. /**
  5974. * @param func - the function to be called
  5975. * @param requester - the object that will request the next frame. Falls back to window.
  5976. */
  5977. Tools.QueueNewFrame = function (func, requester) {
  5978. if (!Tools.IsWindowObjectExist()) {
  5979. return setTimeout(func, 16);
  5980. }
  5981. if (!requester) {
  5982. requester = window;
  5983. }
  5984. if (requester.requestAnimationFrame) {
  5985. return requester.requestAnimationFrame(func);
  5986. }
  5987. else if (requester.msRequestAnimationFrame) {
  5988. return requester.msRequestAnimationFrame(func);
  5989. }
  5990. else if (requester.webkitRequestAnimationFrame) {
  5991. return requester.webkitRequestAnimationFrame(func);
  5992. }
  5993. else if (requester.mozRequestAnimationFrame) {
  5994. return requester.mozRequestAnimationFrame(func);
  5995. }
  5996. else if (requester.oRequestAnimationFrame) {
  5997. return requester.oRequestAnimationFrame(func);
  5998. }
  5999. else {
  6000. return window.setTimeout(func, 16);
  6001. }
  6002. };
  6003. Tools.RequestFullscreen = function (element) {
  6004. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6005. if (!requestFunction)
  6006. return;
  6007. requestFunction.call(element);
  6008. };
  6009. Tools.ExitFullscreen = function () {
  6010. if (document.exitFullscreen) {
  6011. document.exitFullscreen();
  6012. }
  6013. else if (document.mozCancelFullScreen) {
  6014. document.mozCancelFullScreen();
  6015. }
  6016. else if (document.webkitCancelFullScreen) {
  6017. document.webkitCancelFullScreen();
  6018. }
  6019. else if (document.msCancelFullScreen) {
  6020. document.msCancelFullScreen();
  6021. }
  6022. };
  6023. Tools.SetCorsBehavior = function (url, img) {
  6024. if (Tools.CorsBehavior) {
  6025. switch (typeof (Tools.CorsBehavior)) {
  6026. case "function":
  6027. var result = Tools.CorsBehavior(url);
  6028. if (result) {
  6029. img.crossOrigin = result;
  6030. }
  6031. break;
  6032. case "string":
  6033. default:
  6034. img.crossOrigin = Tools.CorsBehavior;
  6035. break;
  6036. }
  6037. }
  6038. };
  6039. // External files
  6040. Tools.CleanUrl = function (url) {
  6041. url = url.replace(/#/mg, "%23");
  6042. return url;
  6043. };
  6044. Tools.LoadImage = function (url, onLoad, onError, database) {
  6045. if (url instanceof ArrayBuffer) {
  6046. url = Tools.EncodeArrayBufferTobase64(url);
  6047. }
  6048. url = Tools.CleanUrl(url);
  6049. url = Tools.PreprocessUrl(url);
  6050. var img = new Image();
  6051. if (url.substr(0, 5) !== "data:") {
  6052. Tools.SetCorsBehavior(url, img);
  6053. }
  6054. img.onload = function () {
  6055. onLoad(img);
  6056. };
  6057. img.onerror = function (err) {
  6058. Tools.Error("Error while trying to load image: " + url);
  6059. if (Tools.UseFallbackTexture) {
  6060. img.src = Tools.fallbackTexture;
  6061. onLoad(img);
  6062. }
  6063. else {
  6064. onError("Error while trying to load image: " + url, err);
  6065. }
  6066. };
  6067. var noIndexedDB = function () {
  6068. img.src = url;
  6069. };
  6070. var loadFromIndexedDB = function () {
  6071. if (database) {
  6072. database.loadImageFromDB(url, img);
  6073. }
  6074. };
  6075. //ANY database to do!
  6076. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6077. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6078. }
  6079. else {
  6080. if (url.indexOf("file:") !== 0) {
  6081. noIndexedDB();
  6082. }
  6083. else {
  6084. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6085. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6086. try {
  6087. var blobURL;
  6088. try {
  6089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6090. }
  6091. catch (ex) {
  6092. // Chrome doesn't support oneTimeOnly parameter
  6093. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6094. }
  6095. img.src = blobURL;
  6096. }
  6097. catch (e) {
  6098. img.src = "";
  6099. }
  6100. }
  6101. else {
  6102. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6103. img.src = Tools.fallbackTexture;
  6104. }
  6105. }
  6106. }
  6107. return img;
  6108. };
  6109. //ANY
  6110. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6111. url = Tools.CleanUrl(url);
  6112. url = Tools.PreprocessUrl(url);
  6113. var request = null;
  6114. var noIndexedDB = function () {
  6115. request = new XMLHttpRequest();
  6116. var loadUrl = Tools.BaseUrl + url;
  6117. request.open('GET', loadUrl, true);
  6118. if (useArrayBuffer) {
  6119. request.responseType = "arraybuffer";
  6120. }
  6121. if (progressCallBack) {
  6122. request.onprogress = progressCallBack;
  6123. }
  6124. request.onreadystatechange = function () {
  6125. var req = request;
  6126. // In case of undefined state in some browsers.
  6127. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6128. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6129. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6130. callback(!useArrayBuffer ? req.responseText : req.response);
  6131. }
  6132. else {
  6133. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6134. if (onError) {
  6135. onError(req, e);
  6136. }
  6137. else {
  6138. throw e;
  6139. }
  6140. }
  6141. }
  6142. };
  6143. request.send(null);
  6144. };
  6145. var loadFromIndexedDB = function () {
  6146. if (database) {
  6147. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6148. }
  6149. };
  6150. if (url.indexOf("file:") !== -1) {
  6151. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6152. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6153. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6154. }
  6155. else {
  6156. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6157. if (onError) {
  6158. var e = new Error(errorMessage);
  6159. onError(undefined, e);
  6160. }
  6161. else {
  6162. Tools.Error(errorMessage);
  6163. }
  6164. }
  6165. }
  6166. else {
  6167. // Caching all files
  6168. if (database && database.enableSceneOffline) {
  6169. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6170. }
  6171. else {
  6172. noIndexedDB();
  6173. }
  6174. }
  6175. return request;
  6176. };
  6177. /**
  6178. * Load a script (identified by an url). When the url returns, the
  6179. * content of this file is added into a new script element, attached to the DOM (body element)
  6180. */
  6181. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6182. var head = document.getElementsByTagName('head')[0];
  6183. var script = document.createElement('script');
  6184. script.type = 'text/javascript';
  6185. script.src = scriptUrl;
  6186. script.onload = function () {
  6187. if (onSuccess) {
  6188. onSuccess();
  6189. }
  6190. };
  6191. script.onerror = function (e) {
  6192. if (onError) {
  6193. onError("Unable to load script", e);
  6194. }
  6195. };
  6196. head.appendChild(script);
  6197. };
  6198. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6199. var reader = new FileReader();
  6200. reader.onload = function (e) {
  6201. //target doesn't have result from ts 1.3
  6202. callback(e.target['result']);
  6203. };
  6204. reader.onprogress = progressCallback;
  6205. reader.readAsDataURL(fileToLoad);
  6206. };
  6207. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6208. var reader = new FileReader();
  6209. reader.onerror = function (e) {
  6210. Tools.Log("Error while reading file: " + fileToLoad.name);
  6211. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6212. };
  6213. reader.onload = function (e) {
  6214. //target doesn't have result from ts 1.3
  6215. callback(e.target['result']);
  6216. };
  6217. if (progressCallBack) {
  6218. reader.onprogress = progressCallBack;
  6219. }
  6220. if (!useArrayBuffer) {
  6221. // Asynchronous read
  6222. reader.readAsText(fileToLoad);
  6223. }
  6224. else {
  6225. reader.readAsArrayBuffer(fileToLoad);
  6226. }
  6227. };
  6228. //returns a downloadable url to a file content.
  6229. Tools.FileAsURL = function (content) {
  6230. var fileBlob = new Blob([content]);
  6231. var url = window.URL || window.webkitURL;
  6232. var link = url.createObjectURL(fileBlob);
  6233. return link;
  6234. };
  6235. // Misc.
  6236. Tools.Format = function (value, decimals) {
  6237. if (decimals === void 0) { decimals = 2; }
  6238. return value.toFixed(decimals);
  6239. };
  6240. Tools.CheckExtends = function (v, min, max) {
  6241. if (v.x < min.x)
  6242. min.x = v.x;
  6243. if (v.y < min.y)
  6244. min.y = v.y;
  6245. if (v.z < min.z)
  6246. min.z = v.z;
  6247. if (v.x > max.x)
  6248. max.x = v.x;
  6249. if (v.y > max.y)
  6250. max.y = v.y;
  6251. if (v.z > max.z)
  6252. max.z = v.z;
  6253. };
  6254. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6255. for (var prop in source) {
  6256. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6257. continue;
  6258. }
  6259. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6260. continue;
  6261. }
  6262. var sourceValue = source[prop];
  6263. var typeOfSourceValue = typeof sourceValue;
  6264. if (typeOfSourceValue === "function") {
  6265. continue;
  6266. }
  6267. if (typeOfSourceValue === "object") {
  6268. if (sourceValue instanceof Array) {
  6269. destination[prop] = [];
  6270. if (sourceValue.length > 0) {
  6271. if (typeof sourceValue[0] == "object") {
  6272. for (var index = 0; index < sourceValue.length; index++) {
  6273. var clonedValue = cloneValue(sourceValue[index], destination);
  6274. if (destination[prop].indexOf(clonedValue) === -1) {
  6275. destination[prop].push(clonedValue);
  6276. }
  6277. }
  6278. }
  6279. else {
  6280. destination[prop] = sourceValue.slice(0);
  6281. }
  6282. }
  6283. }
  6284. else {
  6285. destination[prop] = cloneValue(sourceValue, destination);
  6286. }
  6287. }
  6288. else {
  6289. destination[prop] = sourceValue;
  6290. }
  6291. }
  6292. };
  6293. Tools.IsEmpty = function (obj) {
  6294. for (var i in obj) {
  6295. if (obj.hasOwnProperty(i)) {
  6296. return false;
  6297. }
  6298. }
  6299. return true;
  6300. };
  6301. Tools.RegisterTopRootEvents = function (events) {
  6302. for (var index = 0; index < events.length; index++) {
  6303. var event = events[index];
  6304. window.addEventListener(event.name, event.handler, false);
  6305. try {
  6306. if (window.parent) {
  6307. window.parent.addEventListener(event.name, event.handler, false);
  6308. }
  6309. }
  6310. catch (e) {
  6311. // Silently fails...
  6312. }
  6313. }
  6314. };
  6315. Tools.UnregisterTopRootEvents = function (events) {
  6316. for (var index = 0; index < events.length; index++) {
  6317. var event = events[index];
  6318. window.removeEventListener(event.name, event.handler);
  6319. try {
  6320. if (window.parent) {
  6321. window.parent.removeEventListener(event.name, event.handler);
  6322. }
  6323. }
  6324. catch (e) {
  6325. // Silently fails...
  6326. }
  6327. }
  6328. };
  6329. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6330. if (mimeType === void 0) { mimeType = "image/png"; }
  6331. // Read the contents of the framebuffer
  6332. var numberOfChannelsByLine = width * 4;
  6333. var halfHeight = height / 2;
  6334. //Reading datas from WebGL
  6335. var data = engine.readPixels(0, 0, width, height);
  6336. //To flip image on Y axis.
  6337. for (var i = 0; i < halfHeight; i++) {
  6338. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6339. var currentCell = j + i * numberOfChannelsByLine;
  6340. var targetLine = height - i - 1;
  6341. var targetCell = j + targetLine * numberOfChannelsByLine;
  6342. var temp = data[currentCell];
  6343. data[currentCell] = data[targetCell];
  6344. data[targetCell] = temp;
  6345. }
  6346. }
  6347. // Create a 2D canvas to store the result
  6348. if (!screenshotCanvas) {
  6349. screenshotCanvas = document.createElement('canvas');
  6350. }
  6351. screenshotCanvas.width = width;
  6352. screenshotCanvas.height = height;
  6353. var context = screenshotCanvas.getContext('2d');
  6354. if (context) {
  6355. // Copy the pixels to a 2D canvas
  6356. var imageData = context.createImageData(width, height);
  6357. var castData = (imageData.data);
  6358. castData.set(data);
  6359. context.putImageData(imageData, 0, 0);
  6360. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6361. }
  6362. };
  6363. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6364. if (mimeType === void 0) { mimeType = "image/png"; }
  6365. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6366. if (successCallback) {
  6367. successCallback(base64Image);
  6368. }
  6369. else {
  6370. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6371. if (("download" in document.createElement("a"))) {
  6372. var a = window.document.createElement("a");
  6373. a.href = base64Image;
  6374. var date = new Date();
  6375. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6376. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6377. window.document.body.appendChild(a);
  6378. a.addEventListener("click", function () {
  6379. if (a.parentElement) {
  6380. a.parentElement.removeChild(a);
  6381. }
  6382. });
  6383. a.click();
  6384. //Or opening a new tab with the image if it is not possible to automatically start download.
  6385. }
  6386. else {
  6387. var newWindow = window.open("");
  6388. var img = newWindow.document.createElement("img");
  6389. img.src = base64Image;
  6390. newWindow.document.body.appendChild(img);
  6391. }
  6392. }
  6393. };
  6394. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6395. if (mimeType === void 0) { mimeType = "image/png"; }
  6396. var width;
  6397. var height;
  6398. // If a precision value is specified
  6399. if (size.precision) {
  6400. width = Math.round(engine.getRenderWidth() * size.precision);
  6401. height = Math.round(width / engine.getAspectRatio(camera));
  6402. }
  6403. else if (size.width && size.height) {
  6404. width = size.width;
  6405. height = size.height;
  6406. }
  6407. else if (size.width && !size.height) {
  6408. width = size.width;
  6409. height = Math.round(width / engine.getAspectRatio(camera));
  6410. }
  6411. else if (size.height && !size.width) {
  6412. height = size.height;
  6413. width = Math.round(height * engine.getAspectRatio(camera));
  6414. }
  6415. else if (!isNaN(size)) {
  6416. height = size;
  6417. width = size;
  6418. }
  6419. else {
  6420. Tools.Error("Invalid 'size' parameter !");
  6421. return;
  6422. }
  6423. if (!screenshotCanvas) {
  6424. screenshotCanvas = document.createElement('canvas');
  6425. }
  6426. screenshotCanvas.width = width;
  6427. screenshotCanvas.height = height;
  6428. var renderContext = screenshotCanvas.getContext("2d");
  6429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6430. var newWidth = width;
  6431. var newHeight = newWidth / ratio;
  6432. if (newHeight > height) {
  6433. newHeight = height;
  6434. newWidth = newHeight * ratio;
  6435. }
  6436. var offsetX = Math.max(0, width - newWidth) / 2;
  6437. var offsetY = Math.max(0, height - newHeight) / 2;
  6438. var renderingCanvas = engine.getRenderingCanvas();
  6439. if (renderContext && renderingCanvas) {
  6440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6441. }
  6442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6443. };
  6444. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6445. if (mimeType === void 0) { mimeType = "image/png"; }
  6446. if (samples === void 0) { samples = 1; }
  6447. var width;
  6448. var height;
  6449. //If a precision value is specified
  6450. if (size.precision) {
  6451. width = Math.round(engine.getRenderWidth() * size.precision);
  6452. height = Math.round(width / engine.getAspectRatio(camera));
  6453. size = { width: width, height: height };
  6454. }
  6455. else if (size.width && size.height) {
  6456. width = size.width;
  6457. height = size.height;
  6458. }
  6459. else if (size.width && !size.height) {
  6460. width = size.width;
  6461. height = Math.round(width / engine.getAspectRatio(camera));
  6462. size = { width: width, height: height };
  6463. }
  6464. else if (size.height && !size.width) {
  6465. height = size.height;
  6466. width = Math.round(height * engine.getAspectRatio(camera));
  6467. size = { width: width, height: height };
  6468. }
  6469. else if (!isNaN(size)) {
  6470. height = size;
  6471. width = size;
  6472. }
  6473. else {
  6474. Tools.Error("Invalid 'size' parameter !");
  6475. return;
  6476. }
  6477. var scene = camera.getScene();
  6478. var previousCamera = null;
  6479. if (scene.activeCamera !== camera) {
  6480. previousCamera = scene.activeCamera;
  6481. scene.activeCamera = camera;
  6482. }
  6483. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6484. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6485. texture.renderList = null;
  6486. texture.samples = samples;
  6487. texture.onAfterRenderObservable.add(function () {
  6488. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6489. });
  6490. scene.incrementRenderId();
  6491. scene.resetCachedMaterial();
  6492. texture.render(true);
  6493. texture.dispose();
  6494. if (previousCamera) {
  6495. scene.activeCamera = previousCamera;
  6496. }
  6497. camera.getProjectionMatrix(true); // Force cache refresh;
  6498. };
  6499. // XHR response validator for local file scenario
  6500. Tools.ValidateXHRData = function (xhr, dataType) {
  6501. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6502. if (dataType === void 0) { dataType = 7; }
  6503. try {
  6504. if (dataType & 1) {
  6505. if (xhr.responseText && xhr.responseText.length > 0) {
  6506. return true;
  6507. }
  6508. else if (dataType === 1) {
  6509. return false;
  6510. }
  6511. }
  6512. if (dataType & 2) {
  6513. // Check header width and height since there is no "TGA" magic number
  6514. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6515. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6516. return true;
  6517. }
  6518. else if (dataType === 2) {
  6519. return false;
  6520. }
  6521. }
  6522. if (dataType & 4) {
  6523. // Check for the "DDS" magic number
  6524. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6525. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6526. return true;
  6527. }
  6528. else {
  6529. return false;
  6530. }
  6531. }
  6532. }
  6533. catch (e) {
  6534. // Global protection
  6535. }
  6536. return false;
  6537. };
  6538. /**
  6539. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6540. * Be aware Math.random() could cause collisions, but:
  6541. * "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"
  6542. */
  6543. Tools.RandomId = function () {
  6544. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6545. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6546. return v.toString(16);
  6547. });
  6548. };
  6549. Object.defineProperty(Tools, "NoneLogLevel", {
  6550. get: function () {
  6551. return Tools._NoneLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "MessageLogLevel", {
  6557. get: function () {
  6558. return Tools._MessageLogLevel;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Object.defineProperty(Tools, "WarningLogLevel", {
  6564. get: function () {
  6565. return Tools._WarningLogLevel;
  6566. },
  6567. enumerable: true,
  6568. configurable: true
  6569. });
  6570. Object.defineProperty(Tools, "ErrorLogLevel", {
  6571. get: function () {
  6572. return Tools._ErrorLogLevel;
  6573. },
  6574. enumerable: true,
  6575. configurable: true
  6576. });
  6577. Object.defineProperty(Tools, "AllLogLevel", {
  6578. get: function () {
  6579. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Tools._AddLogEntry = function (entry) {
  6585. Tools._LogCache = entry + Tools._LogCache;
  6586. if (Tools.OnNewCacheEntry) {
  6587. Tools.OnNewCacheEntry(entry);
  6588. }
  6589. };
  6590. Tools._FormatMessage = function (message) {
  6591. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6592. var date = new Date();
  6593. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6594. };
  6595. Tools._LogDisabled = function (message) {
  6596. // nothing to do
  6597. };
  6598. Tools._LogEnabled = function (message) {
  6599. var formattedMessage = Tools._FormatMessage(message);
  6600. console.log("BJS - " + formattedMessage);
  6601. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6602. Tools._AddLogEntry(entry);
  6603. };
  6604. Tools._WarnDisabled = function (message) {
  6605. // nothing to do
  6606. };
  6607. Tools._WarnEnabled = function (message) {
  6608. var formattedMessage = Tools._FormatMessage(message);
  6609. console.warn("BJS - " + formattedMessage);
  6610. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6611. Tools._AddLogEntry(entry);
  6612. };
  6613. Tools._ErrorDisabled = function (message) {
  6614. // nothing to do
  6615. };
  6616. Tools._ErrorEnabled = function (message) {
  6617. Tools.errorsCount++;
  6618. var formattedMessage = Tools._FormatMessage(message);
  6619. console.error("BJS - " + formattedMessage);
  6620. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6621. Tools._AddLogEntry(entry);
  6622. };
  6623. Object.defineProperty(Tools, "LogCache", {
  6624. get: function () {
  6625. return Tools._LogCache;
  6626. },
  6627. enumerable: true,
  6628. configurable: true
  6629. });
  6630. Tools.ClearLogCache = function () {
  6631. Tools._LogCache = "";
  6632. Tools.errorsCount = 0;
  6633. };
  6634. Object.defineProperty(Tools, "LogLevels", {
  6635. set: function (level) {
  6636. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6637. Tools.Log = Tools._LogEnabled;
  6638. }
  6639. else {
  6640. Tools.Log = Tools._LogDisabled;
  6641. }
  6642. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. }
  6645. else {
  6646. Tools.Warn = Tools._WarnDisabled;
  6647. }
  6648. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6649. Tools.Error = Tools._ErrorEnabled;
  6650. }
  6651. else {
  6652. Tools.Error = Tools._ErrorDisabled;
  6653. }
  6654. },
  6655. enumerable: true,
  6656. configurable: true
  6657. });
  6658. Tools.IsWindowObjectExist = function () {
  6659. return (typeof window) !== "undefined";
  6660. };
  6661. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6662. get: function () {
  6663. return Tools._PerformanceNoneLogLevel;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6669. get: function () {
  6670. return Tools._PerformanceUserMarkLogLevel;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6676. get: function () {
  6677. return Tools._PerformanceConsoleLogLevel;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6683. set: function (level) {
  6684. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6685. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6686. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6687. return;
  6688. }
  6689. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6690. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6691. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6692. return;
  6693. }
  6694. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6695. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6696. },
  6697. enumerable: true,
  6698. configurable: true
  6699. });
  6700. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6701. };
  6702. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6703. };
  6704. Tools._StartUserMark = function (counterName, condition) {
  6705. if (condition === void 0) { condition = true; }
  6706. if (!Tools._performance) {
  6707. if (!Tools.IsWindowObjectExist()) {
  6708. return;
  6709. }
  6710. Tools._performance = window.performance;
  6711. }
  6712. if (!condition || !Tools._performance.mark) {
  6713. return;
  6714. }
  6715. Tools._performance.mark(counterName + "-Begin");
  6716. };
  6717. Tools._EndUserMark = function (counterName, condition) {
  6718. if (condition === void 0) { condition = true; }
  6719. if (!condition || !Tools._performance.mark) {
  6720. return;
  6721. }
  6722. Tools._performance.mark(counterName + "-End");
  6723. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6724. };
  6725. Tools._StartPerformanceConsole = function (counterName, condition) {
  6726. if (condition === void 0) { condition = true; }
  6727. if (!condition) {
  6728. return;
  6729. }
  6730. Tools._StartUserMark(counterName, condition);
  6731. if (console.time) {
  6732. console.time(counterName);
  6733. }
  6734. };
  6735. Tools._EndPerformanceConsole = function (counterName, condition) {
  6736. if (condition === void 0) { condition = true; }
  6737. if (!condition) {
  6738. return;
  6739. }
  6740. Tools._EndUserMark(counterName, condition);
  6741. if (console.time) {
  6742. console.timeEnd(counterName);
  6743. }
  6744. };
  6745. Object.defineProperty(Tools, "Now", {
  6746. get: function () {
  6747. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6748. return window.performance.now();
  6749. }
  6750. return new Date().getTime();
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. /**
  6756. * This method will return the name of the class used to create the instance of the given object.
  6757. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6758. * @param object the object to get the class name from
  6759. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6760. */
  6761. Tools.GetClassName = function (object, isType) {
  6762. if (isType === void 0) { isType = false; }
  6763. var name = null;
  6764. if (!isType && object.getClassName) {
  6765. name = object.getClassName();
  6766. }
  6767. else {
  6768. if (object instanceof Object) {
  6769. var classObj = isType ? object : Object.getPrototypeOf(object);
  6770. name = classObj.constructor["__bjsclassName__"];
  6771. }
  6772. if (!name) {
  6773. name = typeof object;
  6774. }
  6775. }
  6776. return name;
  6777. };
  6778. Tools.First = function (array, predicate) {
  6779. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6780. var el = array_1[_i];
  6781. if (predicate(el)) {
  6782. return el;
  6783. }
  6784. }
  6785. return null;
  6786. };
  6787. /**
  6788. * This method will return the name of the full name of the class, including its owning module (if any).
  6789. * 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).
  6790. * @param object the object to get the class name from
  6791. * @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.
  6792. */
  6793. Tools.getFullClassName = function (object, isType) {
  6794. if (isType === void 0) { isType = false; }
  6795. var className = null;
  6796. var moduleName = null;
  6797. if (!isType && object.getClassName) {
  6798. className = object.getClassName();
  6799. }
  6800. else {
  6801. if (object instanceof Object) {
  6802. var classObj = isType ? object : Object.getPrototypeOf(object);
  6803. className = classObj.constructor["__bjsclassName__"];
  6804. moduleName = classObj.constructor["__bjsmoduleName__"];
  6805. }
  6806. if (!className) {
  6807. className = typeof object;
  6808. }
  6809. }
  6810. if (!className) {
  6811. return null;
  6812. }
  6813. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6814. };
  6815. /**
  6816. * 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.
  6817. * @param array
  6818. */
  6819. Tools.arrayOrStringFeeder = function (array) {
  6820. return function (index) {
  6821. if (index >= array.length) {
  6822. return null;
  6823. }
  6824. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6825. if (val && val.getHashCode) {
  6826. val = val.getHashCode();
  6827. }
  6828. if (typeof val === "string") {
  6829. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6830. }
  6831. return val;
  6832. };
  6833. };
  6834. /**
  6835. * Compute the hashCode of a stream of number
  6836. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6837. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6838. * @return the hash code computed
  6839. */
  6840. Tools.hashCodeFromStream = function (feeder) {
  6841. // Based from here: http://stackoverflow.com/a/7616484/802124
  6842. var hash = 0;
  6843. var index = 0;
  6844. var chr = feeder(index++);
  6845. while (chr != null) {
  6846. hash = ((hash << 5) - hash) + chr;
  6847. hash |= 0; // Convert to 32bit integer
  6848. chr = feeder(index++);
  6849. }
  6850. return hash;
  6851. };
  6852. Tools.BaseUrl = "";
  6853. Tools.CorsBehavior = "anonymous";
  6854. Tools.UseFallbackTexture = true;
  6855. /**
  6856. * Use this object to register external classes like custom textures or material
  6857. * to allow the laoders to instantiate them
  6858. */
  6859. Tools.RegisteredExternalClasses = {};
  6860. // Used in case of a texture loading problem
  6861. 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";
  6862. Tools.PreprocessUrl = function (url) {
  6863. return url;
  6864. };
  6865. // Logs
  6866. Tools._NoneLogLevel = 0;
  6867. Tools._MessageLogLevel = 1;
  6868. Tools._WarningLogLevel = 2;
  6869. Tools._ErrorLogLevel = 4;
  6870. Tools._LogCache = "";
  6871. Tools.errorsCount = 0;
  6872. Tools.Log = Tools._LogEnabled;
  6873. Tools.Warn = Tools._WarnEnabled;
  6874. Tools.Error = Tools._ErrorEnabled;
  6875. // Performances
  6876. Tools._PerformanceNoneLogLevel = 0;
  6877. Tools._PerformanceUserMarkLogLevel = 1;
  6878. Tools._PerformanceConsoleLogLevel = 2;
  6879. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6880. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6881. return Tools;
  6882. }());
  6883. BABYLON.Tools = Tools;
  6884. /**
  6885. * This class is used to track a performance counter which is number based.
  6886. * The user has access to many properties which give statistics of different nature
  6887. *
  6888. * The implementer can track two kinds of Performance Counter: time and count
  6889. * 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.
  6890. * 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.
  6891. */
  6892. var PerfCounter = /** @class */ (function () {
  6893. function PerfCounter() {
  6894. this._startMonitoringTime = 0;
  6895. this._min = 0;
  6896. this._max = 0;
  6897. this._average = 0;
  6898. this._lastSecAverage = 0;
  6899. this._current = 0;
  6900. this._totalValueCount = 0;
  6901. this._totalAccumulated = 0;
  6902. this._lastSecAccumulated = 0;
  6903. this._lastSecTime = 0;
  6904. this._lastSecValueCount = 0;
  6905. }
  6906. Object.defineProperty(PerfCounter.prototype, "min", {
  6907. /**
  6908. * Returns the smallest value ever
  6909. */
  6910. get: function () {
  6911. return this._min;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(PerfCounter.prototype, "max", {
  6917. /**
  6918. * Returns the biggest value ever
  6919. */
  6920. get: function () {
  6921. return this._max;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(PerfCounter.prototype, "average", {
  6927. /**
  6928. * Returns the average value since the performance counter is running
  6929. */
  6930. get: function () {
  6931. return this._average;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6937. /**
  6938. * Returns the average value of the last second the counter was monitored
  6939. */
  6940. get: function () {
  6941. return this._lastSecAverage;
  6942. },
  6943. enumerable: true,
  6944. configurable: true
  6945. });
  6946. Object.defineProperty(PerfCounter.prototype, "current", {
  6947. /**
  6948. * Returns the current value
  6949. */
  6950. get: function () {
  6951. return this._current;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(PerfCounter.prototype, "total", {
  6957. get: function () {
  6958. return this._totalAccumulated;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(PerfCounter.prototype, "count", {
  6964. get: function () {
  6965. return this._totalValueCount;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. /**
  6971. * Call this method to start monitoring a new frame.
  6972. * 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.
  6973. */
  6974. PerfCounter.prototype.fetchNewFrame = function () {
  6975. this._totalValueCount++;
  6976. this._current = 0;
  6977. this._lastSecValueCount++;
  6978. };
  6979. /**
  6980. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6981. * @param newCount the count value to add to the monitored count
  6982. * @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.
  6983. */
  6984. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6985. if (!PerfCounter.Enabled) {
  6986. return;
  6987. }
  6988. this._current += newCount;
  6989. if (fetchResult) {
  6990. this._fetchResult();
  6991. }
  6992. };
  6993. /**
  6994. * Start monitoring this performance counter
  6995. */
  6996. PerfCounter.prototype.beginMonitoring = function () {
  6997. if (!PerfCounter.Enabled) {
  6998. return;
  6999. }
  7000. this._startMonitoringTime = Tools.Now;
  7001. };
  7002. /**
  7003. * Compute the time lapsed since the previous beginMonitoring() call.
  7004. * @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
  7005. */
  7006. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7007. if (newFrame === void 0) { newFrame = true; }
  7008. if (!PerfCounter.Enabled) {
  7009. return;
  7010. }
  7011. if (newFrame) {
  7012. this.fetchNewFrame();
  7013. }
  7014. var currentTime = Tools.Now;
  7015. this._current = currentTime - this._startMonitoringTime;
  7016. if (newFrame) {
  7017. this._fetchResult();
  7018. }
  7019. };
  7020. PerfCounter.prototype._fetchResult = function () {
  7021. this._totalAccumulated += this._current;
  7022. this._lastSecAccumulated += this._current;
  7023. // Min/Max update
  7024. this._min = Math.min(this._min, this._current);
  7025. this._max = Math.max(this._max, this._current);
  7026. this._average = this._totalAccumulated / this._totalValueCount;
  7027. // Reset last sec?
  7028. var now = Tools.Now;
  7029. if ((now - this._lastSecTime) > 1000) {
  7030. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7031. this._lastSecTime = now;
  7032. this._lastSecAccumulated = 0;
  7033. this._lastSecValueCount = 0;
  7034. }
  7035. };
  7036. PerfCounter.Enabled = true;
  7037. return PerfCounter;
  7038. }());
  7039. BABYLON.PerfCounter = PerfCounter;
  7040. /**
  7041. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7042. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7043. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7044. * @param name The name of the class, case should be preserved
  7045. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7046. */
  7047. function className(name, module) {
  7048. return function (target) {
  7049. target["__bjsclassName__"] = name;
  7050. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7051. };
  7052. }
  7053. BABYLON.className = className;
  7054. /**
  7055. * An implementation of a loop for asynchronous functions.
  7056. */
  7057. var AsyncLoop = /** @class */ (function () {
  7058. /**
  7059. * Constroctor.
  7060. * @param iterations the number of iterations.
  7061. * @param _fn the function to run each iteration
  7062. * @param _successCallback the callback that will be called upon succesful execution
  7063. * @param offset starting offset.
  7064. */
  7065. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7066. if (offset === void 0) { offset = 0; }
  7067. this.iterations = iterations;
  7068. this._fn = _fn;
  7069. this._successCallback = _successCallback;
  7070. this.index = offset - 1;
  7071. this._done = false;
  7072. }
  7073. /**
  7074. * Execute the next iteration. Must be called after the last iteration was finished.
  7075. */
  7076. AsyncLoop.prototype.executeNext = function () {
  7077. if (!this._done) {
  7078. if (this.index + 1 < this.iterations) {
  7079. ++this.index;
  7080. this._fn(this);
  7081. }
  7082. else {
  7083. this.breakLoop();
  7084. }
  7085. }
  7086. };
  7087. /**
  7088. * Break the loop and run the success callback.
  7089. */
  7090. AsyncLoop.prototype.breakLoop = function () {
  7091. this._done = true;
  7092. this._successCallback();
  7093. };
  7094. /**
  7095. * Helper function
  7096. */
  7097. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7098. if (offset === void 0) { offset = 0; }
  7099. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7100. loop.executeNext();
  7101. return loop;
  7102. };
  7103. /**
  7104. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7105. * @param iterations total number of iterations
  7106. * @param syncedIterations number of synchronous iterations in each async iteration.
  7107. * @param fn the function to call each iteration.
  7108. * @param callback a success call back that will be called when iterating stops.
  7109. * @param breakFunction a break condition (optional)
  7110. * @param timeout timeout settings for the setTimeout function. default - 0.
  7111. * @constructor
  7112. */
  7113. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7114. if (timeout === void 0) { timeout = 0; }
  7115. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7116. if (breakFunction && breakFunction())
  7117. loop.breakLoop();
  7118. else {
  7119. setTimeout(function () {
  7120. for (var i = 0; i < syncedIterations; ++i) {
  7121. var iteration = (loop.index * syncedIterations) + i;
  7122. if (iteration >= iterations)
  7123. break;
  7124. fn(iteration);
  7125. if (breakFunction && breakFunction()) {
  7126. loop.breakLoop();
  7127. break;
  7128. }
  7129. }
  7130. loop.executeNext();
  7131. }, timeout);
  7132. }
  7133. }, callback);
  7134. };
  7135. return AsyncLoop;
  7136. }());
  7137. BABYLON.AsyncLoop = AsyncLoop;
  7138. })(BABYLON || (BABYLON = {}));
  7139. //# sourceMappingURL=babylon.tools.js.map
  7140. var BABYLON;
  7141. (function (BABYLON) {
  7142. var Internals;
  7143. (function (Internals) {
  7144. var _AlphaState = /** @class */ (function () {
  7145. /**
  7146. * Initializes the state.
  7147. */
  7148. function _AlphaState() {
  7149. this._isAlphaBlendDirty = false;
  7150. this._isBlendFunctionParametersDirty = false;
  7151. this._isBlendEquationParametersDirty = false;
  7152. this._isBlendConstantsDirty = false;
  7153. this._alphaBlend = false;
  7154. this._blendFunctionParameters = new Array(4);
  7155. this._blendEquationParameters = new Array(2);
  7156. this._blendConstants = new Array(4);
  7157. this.reset();
  7158. }
  7159. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7160. get: function () {
  7161. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7162. },
  7163. enumerable: true,
  7164. configurable: true
  7165. });
  7166. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7167. get: function () {
  7168. return this._alphaBlend;
  7169. },
  7170. set: function (value) {
  7171. if (this._alphaBlend === value) {
  7172. return;
  7173. }
  7174. this._alphaBlend = value;
  7175. this._isAlphaBlendDirty = true;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7181. if (this._blendConstants[0] === r &&
  7182. this._blendConstants[1] === g &&
  7183. this._blendConstants[2] === b &&
  7184. this._blendConstants[3] === a) {
  7185. return;
  7186. }
  7187. this._blendConstants[0] = r;
  7188. this._blendConstants[1] = g;
  7189. this._blendConstants[2] = b;
  7190. this._blendConstants[3] = a;
  7191. this._isBlendConstantsDirty = true;
  7192. };
  7193. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7194. if (this._blendFunctionParameters[0] === value0 &&
  7195. this._blendFunctionParameters[1] === value1 &&
  7196. this._blendFunctionParameters[2] === value2 &&
  7197. this._blendFunctionParameters[3] === value3) {
  7198. return;
  7199. }
  7200. this._blendFunctionParameters[0] = value0;
  7201. this._blendFunctionParameters[1] = value1;
  7202. this._blendFunctionParameters[2] = value2;
  7203. this._blendFunctionParameters[3] = value3;
  7204. this._isBlendFunctionParametersDirty = true;
  7205. };
  7206. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7207. if (this._blendEquationParameters[0] === rgb &&
  7208. this._blendEquationParameters[1] === alpha) {
  7209. return;
  7210. }
  7211. this._blendEquationParameters[0] = rgb;
  7212. this._blendEquationParameters[1] = alpha;
  7213. this._isBlendEquationParametersDirty = true;
  7214. };
  7215. _AlphaState.prototype.reset = function () {
  7216. this._alphaBlend = false;
  7217. this._blendFunctionParameters[0] = null;
  7218. this._blendFunctionParameters[1] = null;
  7219. this._blendFunctionParameters[2] = null;
  7220. this._blendFunctionParameters[3] = null;
  7221. this._blendEquationParameters[0] = null;
  7222. this._blendEquationParameters[1] = null;
  7223. this._blendConstants[0] = null;
  7224. this._blendConstants[1] = null;
  7225. this._blendConstants[2] = null;
  7226. this._blendConstants[3] = null;
  7227. this._isAlphaBlendDirty = true;
  7228. this._isBlendFunctionParametersDirty = false;
  7229. this._isBlendEquationParametersDirty = false;
  7230. this._isBlendConstantsDirty = false;
  7231. };
  7232. _AlphaState.prototype.apply = function (gl) {
  7233. if (!this.isDirty) {
  7234. return;
  7235. }
  7236. // Alpha blend
  7237. if (this._isAlphaBlendDirty) {
  7238. if (this._alphaBlend) {
  7239. gl.enable(gl.BLEND);
  7240. }
  7241. else {
  7242. gl.disable(gl.BLEND);
  7243. }
  7244. this._isAlphaBlendDirty = false;
  7245. }
  7246. // Alpha function
  7247. if (this._isBlendFunctionParametersDirty) {
  7248. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7249. this._isBlendFunctionParametersDirty = false;
  7250. }
  7251. // Alpha equation
  7252. if (this._isBlendEquationParametersDirty) {
  7253. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7254. this._isBlendEquationParametersDirty = false;
  7255. }
  7256. // Constants
  7257. if (this._isBlendConstantsDirty) {
  7258. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7259. this._isBlendConstantsDirty = false;
  7260. }
  7261. };
  7262. return _AlphaState;
  7263. }());
  7264. Internals._AlphaState = _AlphaState;
  7265. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7266. })(BABYLON || (BABYLON = {}));
  7267. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7268. var BABYLON;
  7269. (function (BABYLON) {
  7270. var Internals;
  7271. (function (Internals) {
  7272. var _DepthCullingState = /** @class */ (function () {
  7273. /**
  7274. * Initializes the state.
  7275. */
  7276. function _DepthCullingState() {
  7277. this._isDepthTestDirty = false;
  7278. this._isDepthMaskDirty = false;
  7279. this._isDepthFuncDirty = false;
  7280. this._isCullFaceDirty = false;
  7281. this._isCullDirty = false;
  7282. this._isZOffsetDirty = false;
  7283. this.reset();
  7284. }
  7285. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7286. get: function () {
  7287. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7288. },
  7289. enumerable: true,
  7290. configurable: true
  7291. });
  7292. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7293. get: function () {
  7294. return this._zOffset;
  7295. },
  7296. set: function (value) {
  7297. if (this._zOffset === value) {
  7298. return;
  7299. }
  7300. this._zOffset = value;
  7301. this._isZOffsetDirty = true;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7307. get: function () {
  7308. return this._cullFace;
  7309. },
  7310. set: function (value) {
  7311. if (this._cullFace === value) {
  7312. return;
  7313. }
  7314. this._cullFace = value;
  7315. this._isCullFaceDirty = true;
  7316. },
  7317. enumerable: true,
  7318. configurable: true
  7319. });
  7320. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7321. get: function () {
  7322. return this._cull;
  7323. },
  7324. set: function (value) {
  7325. if (this._cull === value) {
  7326. return;
  7327. }
  7328. this._cull = value;
  7329. this._isCullDirty = true;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7335. get: function () {
  7336. return this._depthFunc;
  7337. },
  7338. set: function (value) {
  7339. if (this._depthFunc === value) {
  7340. return;
  7341. }
  7342. this._depthFunc = value;
  7343. this._isDepthFuncDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7349. get: function () {
  7350. return this._depthMask;
  7351. },
  7352. set: function (value) {
  7353. if (this._depthMask === value) {
  7354. return;
  7355. }
  7356. this._depthMask = value;
  7357. this._isDepthMaskDirty = true;
  7358. },
  7359. enumerable: true,
  7360. configurable: true
  7361. });
  7362. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7363. get: function () {
  7364. return this._depthTest;
  7365. },
  7366. set: function (value) {
  7367. if (this._depthTest === value) {
  7368. return;
  7369. }
  7370. this._depthTest = value;
  7371. this._isDepthTestDirty = true;
  7372. },
  7373. enumerable: true,
  7374. configurable: true
  7375. });
  7376. _DepthCullingState.prototype.reset = function () {
  7377. this._depthMask = true;
  7378. this._depthTest = true;
  7379. this._depthFunc = null;
  7380. this._cullFace = null;
  7381. this._cull = null;
  7382. this._zOffset = 0;
  7383. this._isDepthTestDirty = true;
  7384. this._isDepthMaskDirty = true;
  7385. this._isDepthFuncDirty = false;
  7386. this._isCullFaceDirty = false;
  7387. this._isCullDirty = false;
  7388. this._isZOffsetDirty = false;
  7389. };
  7390. _DepthCullingState.prototype.apply = function (gl) {
  7391. if (!this.isDirty) {
  7392. return;
  7393. }
  7394. // Cull
  7395. if (this._isCullDirty) {
  7396. if (this.cull) {
  7397. gl.enable(gl.CULL_FACE);
  7398. }
  7399. else {
  7400. gl.disable(gl.CULL_FACE);
  7401. }
  7402. this._isCullDirty = false;
  7403. }
  7404. // Cull face
  7405. if (this._isCullFaceDirty) {
  7406. gl.cullFace(this.cullFace);
  7407. this._isCullFaceDirty = false;
  7408. }
  7409. // Depth mask
  7410. if (this._isDepthMaskDirty) {
  7411. gl.depthMask(this.depthMask);
  7412. this._isDepthMaskDirty = false;
  7413. }
  7414. // Depth test
  7415. if (this._isDepthTestDirty) {
  7416. if (this.depthTest) {
  7417. gl.enable(gl.DEPTH_TEST);
  7418. }
  7419. else {
  7420. gl.disable(gl.DEPTH_TEST);
  7421. }
  7422. this._isDepthTestDirty = false;
  7423. }
  7424. // Depth func
  7425. if (this._isDepthFuncDirty) {
  7426. gl.depthFunc(this.depthFunc);
  7427. this._isDepthFuncDirty = false;
  7428. }
  7429. // zOffset
  7430. if (this._isZOffsetDirty) {
  7431. if (this.zOffset) {
  7432. gl.enable(gl.POLYGON_OFFSET_FILL);
  7433. gl.polygonOffset(this.zOffset, 0);
  7434. }
  7435. else {
  7436. gl.disable(gl.POLYGON_OFFSET_FILL);
  7437. }
  7438. this._isZOffsetDirty = false;
  7439. }
  7440. };
  7441. return _DepthCullingState;
  7442. }());
  7443. Internals._DepthCullingState = _DepthCullingState;
  7444. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7445. })(BABYLON || (BABYLON = {}));
  7446. //# sourceMappingURL=babylon.depthCullingState.js.map
  7447. var BABYLON;
  7448. (function (BABYLON) {
  7449. var Internals;
  7450. (function (Internals) {
  7451. var _StencilState = /** @class */ (function () {
  7452. function _StencilState() {
  7453. this._isStencilTestDirty = false;
  7454. this._isStencilMaskDirty = false;
  7455. this._isStencilFuncDirty = false;
  7456. this._isStencilOpDirty = false;
  7457. this.reset();
  7458. }
  7459. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7460. get: function () {
  7461. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7467. get: function () {
  7468. return this._stencilFunc;
  7469. },
  7470. set: function (value) {
  7471. if (this._stencilFunc === value) {
  7472. return;
  7473. }
  7474. this._stencilFunc = value;
  7475. this._isStencilFuncDirty = true;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7481. get: function () {
  7482. return this._stencilFuncRef;
  7483. },
  7484. set: function (value) {
  7485. if (this._stencilFuncRef === value) {
  7486. return;
  7487. }
  7488. this._stencilFuncRef = value;
  7489. this._isStencilFuncDirty = true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7495. get: function () {
  7496. return this._stencilFuncMask;
  7497. },
  7498. set: function (value) {
  7499. if (this._stencilFuncMask === value) {
  7500. return;
  7501. }
  7502. this._stencilFuncMask = value;
  7503. this._isStencilFuncDirty = true;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7509. get: function () {
  7510. return this._stencilOpStencilFail;
  7511. },
  7512. set: function (value) {
  7513. if (this._stencilOpStencilFail === value) {
  7514. return;
  7515. }
  7516. this._stencilOpStencilFail = value;
  7517. this._isStencilOpDirty = true;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7523. get: function () {
  7524. return this._stencilOpDepthFail;
  7525. },
  7526. set: function (value) {
  7527. if (this._stencilOpDepthFail === value) {
  7528. return;
  7529. }
  7530. this._stencilOpDepthFail = value;
  7531. this._isStencilOpDirty = true;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7537. get: function () {
  7538. return this._stencilOpStencilDepthPass;
  7539. },
  7540. set: function (value) {
  7541. if (this._stencilOpStencilDepthPass === value) {
  7542. return;
  7543. }
  7544. this._stencilOpStencilDepthPass = value;
  7545. this._isStencilOpDirty = true;
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7551. get: function () {
  7552. return this._stencilMask;
  7553. },
  7554. set: function (value) {
  7555. if (this._stencilMask === value) {
  7556. return;
  7557. }
  7558. this._stencilMask = value;
  7559. this._isStencilMaskDirty = true;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7565. get: function () {
  7566. return this._stencilTest;
  7567. },
  7568. set: function (value) {
  7569. if (this._stencilTest === value) {
  7570. return;
  7571. }
  7572. this._stencilTest = value;
  7573. this._isStencilTestDirty = true;
  7574. },
  7575. enumerable: true,
  7576. configurable: true
  7577. });
  7578. _StencilState.prototype.reset = function () {
  7579. this._stencilTest = false;
  7580. this._stencilMask = 0xFF;
  7581. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7582. this._stencilFuncRef = 1;
  7583. this._stencilFuncMask = 0xFF;
  7584. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7585. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7586. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7587. this._isStencilTestDirty = true;
  7588. this._isStencilMaskDirty = true;
  7589. this._isStencilFuncDirty = true;
  7590. this._isStencilOpDirty = true;
  7591. };
  7592. _StencilState.prototype.apply = function (gl) {
  7593. if (!this.isDirty) {
  7594. return;
  7595. }
  7596. // Stencil test
  7597. if (this._isStencilTestDirty) {
  7598. if (this.stencilTest) {
  7599. gl.enable(gl.STENCIL_TEST);
  7600. }
  7601. else {
  7602. gl.disable(gl.STENCIL_TEST);
  7603. }
  7604. this._isStencilTestDirty = false;
  7605. }
  7606. // Stencil mask
  7607. if (this._isStencilMaskDirty) {
  7608. gl.stencilMask(this.stencilMask);
  7609. this._isStencilMaskDirty = false;
  7610. }
  7611. // Stencil func
  7612. if (this._isStencilFuncDirty) {
  7613. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7614. this._isStencilFuncDirty = false;
  7615. }
  7616. // Stencil op
  7617. if (this._isStencilOpDirty) {
  7618. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7619. this._isStencilOpDirty = false;
  7620. }
  7621. };
  7622. return _StencilState;
  7623. }());
  7624. Internals._StencilState = _StencilState;
  7625. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7626. })(BABYLON || (BABYLON = {}));
  7627. //# sourceMappingURL=babylon.stencilState.js.map
  7628. var BABYLON;
  7629. (function (BABYLON) {
  7630. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7631. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7632. };
  7633. var compileRawShader = function (gl, source, type) {
  7634. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7635. gl.shaderSource(shader, source);
  7636. gl.compileShader(shader);
  7637. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7638. var log = gl.getShaderInfoLog(shader);
  7639. if (log) {
  7640. throw new Error(log);
  7641. }
  7642. }
  7643. if (!shader) {
  7644. throw new Error("Something went wrong while compile the shader.");
  7645. }
  7646. return shader;
  7647. };
  7648. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7649. var magFilter = gl.NEAREST;
  7650. var minFilter = gl.NEAREST;
  7651. switch (samplingMode) {
  7652. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7653. magFilter = gl.LINEAR;
  7654. if (generateMipMaps) {
  7655. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7656. }
  7657. else {
  7658. minFilter = gl.LINEAR;
  7659. }
  7660. break;
  7661. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7662. magFilter = gl.LINEAR;
  7663. if (generateMipMaps) {
  7664. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7665. }
  7666. else {
  7667. minFilter = gl.LINEAR;
  7668. }
  7669. break;
  7670. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7671. magFilter = gl.NEAREST;
  7672. if (generateMipMaps) {
  7673. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7674. }
  7675. else {
  7676. minFilter = gl.NEAREST;
  7677. }
  7678. break;
  7679. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7680. magFilter = gl.NEAREST;
  7681. if (generateMipMaps) {
  7682. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7683. }
  7684. else {
  7685. minFilter = gl.NEAREST;
  7686. }
  7687. break;
  7688. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7689. magFilter = gl.NEAREST;
  7690. if (generateMipMaps) {
  7691. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7692. }
  7693. else {
  7694. minFilter = gl.LINEAR;
  7695. }
  7696. break;
  7697. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7698. magFilter = gl.NEAREST;
  7699. if (generateMipMaps) {
  7700. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7701. }
  7702. else {
  7703. minFilter = gl.LINEAR;
  7704. }
  7705. break;
  7706. case BABYLON.Texture.NEAREST_LINEAR:
  7707. magFilter = gl.NEAREST;
  7708. minFilter = gl.LINEAR;
  7709. break;
  7710. case BABYLON.Texture.NEAREST_NEAREST:
  7711. magFilter = gl.NEAREST;
  7712. minFilter = gl.NEAREST;
  7713. break;
  7714. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7715. magFilter = gl.LINEAR;
  7716. if (generateMipMaps) {
  7717. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7718. }
  7719. else {
  7720. minFilter = gl.NEAREST;
  7721. }
  7722. break;
  7723. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7724. magFilter = gl.LINEAR;
  7725. if (generateMipMaps) {
  7726. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7727. }
  7728. else {
  7729. minFilter = gl.NEAREST;
  7730. }
  7731. break;
  7732. case BABYLON.Texture.LINEAR_LINEAR:
  7733. magFilter = gl.LINEAR;
  7734. minFilter = gl.LINEAR;
  7735. break;
  7736. case BABYLON.Texture.LINEAR_NEAREST:
  7737. magFilter = gl.LINEAR;
  7738. minFilter = gl.NEAREST;
  7739. break;
  7740. }
  7741. return {
  7742. min: minFilter,
  7743. mag: magFilter
  7744. };
  7745. };
  7746. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7747. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7748. var img;
  7749. var onload = function () {
  7750. loadedImages[index] = img;
  7751. loadedImages._internalCount++;
  7752. if (scene) {
  7753. scene._removePendingData(img);
  7754. }
  7755. if (loadedImages._internalCount === 6) {
  7756. onfinish(loadedImages);
  7757. }
  7758. };
  7759. var onerror = function (message, exception) {
  7760. if (scene) {
  7761. scene._removePendingData(img);
  7762. }
  7763. if (onErrorCallBack) {
  7764. onErrorCallBack(message, exception);
  7765. }
  7766. };
  7767. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7768. if (scene) {
  7769. scene._addPendingData(img);
  7770. }
  7771. };
  7772. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7773. if (onError === void 0) { onError = null; }
  7774. var loadedImages = [];
  7775. loadedImages._internalCount = 0;
  7776. for (var index = 0; index < 6; index++) {
  7777. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7778. }
  7779. };
  7780. var BufferPointer = /** @class */ (function () {
  7781. function BufferPointer() {
  7782. }
  7783. return BufferPointer;
  7784. }());
  7785. var InstancingAttributeInfo = /** @class */ (function () {
  7786. function InstancingAttributeInfo() {
  7787. }
  7788. return InstancingAttributeInfo;
  7789. }());
  7790. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7791. /**
  7792. * Define options used to create a render target texture
  7793. */
  7794. var RenderTargetCreationOptions = /** @class */ (function () {
  7795. function RenderTargetCreationOptions() {
  7796. }
  7797. return RenderTargetCreationOptions;
  7798. }());
  7799. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7800. /**
  7801. * Regroup several parameters relative to the browser in use
  7802. */
  7803. var EngineCapabilities = /** @class */ (function () {
  7804. function EngineCapabilities() {
  7805. }
  7806. return EngineCapabilities;
  7807. }());
  7808. BABYLON.EngineCapabilities = EngineCapabilities;
  7809. /**
  7810. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7811. */
  7812. var Engine = /** @class */ (function () {
  7813. /**
  7814. * @constructor
  7815. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7816. * @param {boolean} [antialias] - enable antialias
  7817. * @param options - further options to be sent to the getContext function
  7818. */
  7819. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7820. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7821. var _this = this;
  7822. // Public members
  7823. this.forcePOTTextures = false;
  7824. this.isFullscreen = false;
  7825. this.isPointerLock = false;
  7826. this.cullBackFaces = true;
  7827. this.renderEvenInBackground = true;
  7828. this.preventCacheWipeBetweenFrames = false;
  7829. // To enable/disable IDB support and avoid XHR on .manifest
  7830. this.enableOfflineSupport = false;
  7831. this.scenes = new Array();
  7832. this.postProcesses = new Array();
  7833. // Observables
  7834. /**
  7835. * Observable event triggered each time the rendering canvas is resized
  7836. */
  7837. this.onResizeObservable = new BABYLON.Observable();
  7838. /**
  7839. * Observable event triggered each time the canvas loses focus
  7840. */
  7841. this.onCanvasBlurObservable = new BABYLON.Observable();
  7842. /**
  7843. * Observable event triggered each time the canvas gains focus
  7844. */
  7845. this.onCanvasFocusObservable = new BABYLON.Observable();
  7846. /**
  7847. * Observable event triggered each time the canvas receives pointerout event
  7848. */
  7849. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7850. /**
  7851. * Observable event triggered before each texture is initialized
  7852. */
  7853. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7854. //WebVR
  7855. this._vrDisplay = undefined;
  7856. this._vrSupported = false;
  7857. this._vrExclusivePointerMode = false;
  7858. // Uniform buffers list
  7859. this.disableUniformBuffers = false;
  7860. this._uniformBuffers = new Array();
  7861. // Observables
  7862. /**
  7863. * Observable raised when the engine begins a new frame
  7864. */
  7865. this.onBeginFrameObservable = new BABYLON.Observable();
  7866. /**
  7867. * Observable raised when the engine ends the current frame
  7868. */
  7869. this.onEndFrameObservable = new BABYLON.Observable();
  7870. /**
  7871. * Observable raised when the engine is about to compile a shader
  7872. */
  7873. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7874. /**
  7875. * Observable raised when the engine has jsut compiled a shader
  7876. */
  7877. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7878. this._windowIsBackground = false;
  7879. this._webGLVersion = 1.0;
  7880. this._badOS = false;
  7881. this._badDesktopOS = false;
  7882. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7883. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7884. this.onVRRequestPresentStart = new BABYLON.Observable();
  7885. this._colorWrite = true;
  7886. this._drawCalls = new BABYLON.PerfCounter();
  7887. this._renderingQueueLaunched = false;
  7888. this._activeRenderLoops = new Array();
  7889. // Deterministic lockstepMaxSteps
  7890. this._deterministicLockstep = false;
  7891. this._lockstepMaxSteps = 4;
  7892. // Lost context
  7893. this.onContextLostObservable = new BABYLON.Observable();
  7894. this.onContextRestoredObservable = new BABYLON.Observable();
  7895. this._contextWasLost = false;
  7896. this._doNotHandleContextLost = false;
  7897. // FPS
  7898. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7899. this._fps = 60;
  7900. this._deltaTime = 0;
  7901. /**
  7902. * Turn this value on if you want to pause FPS computation when in background
  7903. */
  7904. this.disablePerformanceMonitorInBackground = false;
  7905. // States
  7906. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7907. this._stencilState = new BABYLON.Internals._StencilState();
  7908. this._alphaState = new BABYLON.Internals._AlphaState();
  7909. this._alphaMode = Engine.ALPHA_DISABLE;
  7910. // Cache
  7911. this._internalTexturesCache = new Array();
  7912. this._activeTexturesCache = {};
  7913. this._compiledEffects = {};
  7914. this._vertexAttribArraysEnabled = [];
  7915. this._uintIndicesCurrentlySet = false;
  7916. this._currentBoundBuffer = new Array();
  7917. this._currentBufferPointers = new Array();
  7918. this._currentInstanceLocations = new Array();
  7919. this._currentInstanceBuffers = new Array();
  7920. this._vaoRecordInProgress = false;
  7921. this._mustWipeVertexAttributes = false;
  7922. // Hardware supported Compressed Textures
  7923. this._texturesSupported = new Array();
  7924. this._onVRFullScreenTriggered = function () {
  7925. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7926. //get the old size before we change
  7927. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7928. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7929. //get the width and height, change the render size
  7930. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7931. _this.setHardwareScalingLevel(1);
  7932. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7933. }
  7934. else {
  7935. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7936. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7937. }
  7938. };
  7939. var canvas = null;
  7940. Engine.Instances.push(this);
  7941. if (!canvasOrContext) {
  7942. return;
  7943. }
  7944. options = options || {};
  7945. if (canvasOrContext.getContext) {
  7946. canvas = canvasOrContext;
  7947. this._renderingCanvas = canvas;
  7948. if (antialias != null) {
  7949. options.antialias = antialias;
  7950. }
  7951. if (options.deterministicLockstep === undefined) {
  7952. options.deterministicLockstep = false;
  7953. }
  7954. if (options.lockstepMaxSteps === undefined) {
  7955. options.lockstepMaxSteps = 4;
  7956. }
  7957. if (options.preserveDrawingBuffer === undefined) {
  7958. options.preserveDrawingBuffer = false;
  7959. }
  7960. if (options.audioEngine === undefined) {
  7961. options.audioEngine = true;
  7962. }
  7963. if (options.stencil === undefined) {
  7964. options.stencil = true;
  7965. }
  7966. this._deterministicLockstep = options.deterministicLockstep;
  7967. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7968. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7969. // GL
  7970. if (!options.disableWebGL2Support) {
  7971. try {
  7972. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7973. if (this._gl) {
  7974. this._webGLVersion = 2.0;
  7975. }
  7976. }
  7977. catch (e) {
  7978. // Do nothing
  7979. }
  7980. }
  7981. if (!this._gl) {
  7982. if (!canvas) {
  7983. throw new Error("The provided canvas is null or undefined.");
  7984. }
  7985. try {
  7986. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7987. }
  7988. catch (e) {
  7989. throw new Error("WebGL not supported");
  7990. }
  7991. }
  7992. if (!this._gl) {
  7993. throw new Error("WebGL not supported");
  7994. }
  7995. this._onCanvasFocus = function () {
  7996. _this.onCanvasFocusObservable.notifyObservers(_this);
  7997. };
  7998. this._onCanvasBlur = function () {
  7999. _this.onCanvasBlurObservable.notifyObservers(_this);
  8000. };
  8001. canvas.addEventListener("focus", this._onCanvasFocus);
  8002. canvas.addEventListener("blur", this._onCanvasBlur);
  8003. this._onBlur = function () {
  8004. if (_this.disablePerformanceMonitorInBackground) {
  8005. _this._performanceMonitor.disable();
  8006. }
  8007. _this._windowIsBackground = true;
  8008. };
  8009. this._onFocus = function () {
  8010. if (_this.disablePerformanceMonitorInBackground) {
  8011. _this._performanceMonitor.enable();
  8012. }
  8013. _this._windowIsBackground = false;
  8014. };
  8015. this._onCanvasPointerOut = function () {
  8016. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8017. };
  8018. window.addEventListener("blur", this._onBlur);
  8019. window.addEventListener("focus", this._onFocus);
  8020. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8021. // Context lost
  8022. if (!this._doNotHandleContextLost) {
  8023. this._onContextLost = function (evt) {
  8024. evt.preventDefault();
  8025. _this._contextWasLost = true;
  8026. BABYLON.Tools.Warn("WebGL context lost.");
  8027. _this.onContextLostObservable.notifyObservers(_this);
  8028. };
  8029. this._onContextRestored = function (evt) {
  8030. // Adding a timeout to avoid race condition at browser level
  8031. setTimeout(function () {
  8032. // Rebuild gl context
  8033. _this._initGLContext();
  8034. // Rebuild effects
  8035. _this._rebuildEffects();
  8036. // Rebuild textures
  8037. _this._rebuildInternalTextures();
  8038. // Rebuild buffers
  8039. _this._rebuildBuffers();
  8040. // Cache
  8041. _this.wipeCaches(true);
  8042. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8043. _this.onContextRestoredObservable.notifyObservers(_this);
  8044. _this._contextWasLost = false;
  8045. }, 0);
  8046. };
  8047. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8048. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8049. }
  8050. }
  8051. else {
  8052. this._gl = canvasOrContext;
  8053. this._renderingCanvas = this._gl.canvas;
  8054. if (this._gl.renderbufferStorageMultisample) {
  8055. this._webGLVersion = 2.0;
  8056. }
  8057. options.stencil = this._gl.getContextAttributes().stencil;
  8058. }
  8059. // Viewport
  8060. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8061. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8062. this.resize();
  8063. this._isStencilEnable = options.stencil ? true : false;
  8064. this._initGLContext();
  8065. if (canvas) {
  8066. // Fullscreen
  8067. this._onFullscreenChange = function () {
  8068. if (document.fullscreen !== undefined) {
  8069. _this.isFullscreen = document.fullscreen;
  8070. }
  8071. else if (document.mozFullScreen !== undefined) {
  8072. _this.isFullscreen = document.mozFullScreen;
  8073. }
  8074. else if (document.webkitIsFullScreen !== undefined) {
  8075. _this.isFullscreen = document.webkitIsFullScreen;
  8076. }
  8077. else if (document.msIsFullScreen !== undefined) {
  8078. _this.isFullscreen = document.msIsFullScreen;
  8079. }
  8080. // Pointer lock
  8081. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8082. canvas.requestPointerLock = canvas.requestPointerLock ||
  8083. canvas.msRequestPointerLock ||
  8084. canvas.mozRequestPointerLock ||
  8085. canvas.webkitRequestPointerLock;
  8086. if (canvas.requestPointerLock) {
  8087. canvas.requestPointerLock();
  8088. }
  8089. }
  8090. };
  8091. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8092. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8093. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8094. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8095. // Pointer lock
  8096. this._onPointerLockChange = function () {
  8097. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8098. document.webkitPointerLockElement === canvas ||
  8099. document.msPointerLockElement === canvas ||
  8100. document.pointerLockElement === canvas);
  8101. };
  8102. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8103. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8104. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8105. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8106. this._onVRDisplayPointerRestricted = function () {
  8107. if (canvas) {
  8108. canvas.requestPointerLock();
  8109. }
  8110. };
  8111. this._onVRDisplayPointerUnrestricted = function () {
  8112. document.exitPointerLock();
  8113. };
  8114. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8115. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8116. }
  8117. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8118. Engine.audioEngine = new BABYLON.AudioEngine();
  8119. }
  8120. // Prepare buffer pointers
  8121. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8122. this._currentBufferPointers[i] = new BufferPointer();
  8123. }
  8124. // Load WebVR Devices
  8125. if (options.autoEnableWebVR) {
  8126. this.initWebVR();
  8127. }
  8128. // Detect if we are running on a faulty buggy OS.
  8129. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8130. // Detect if we are running on a faulty buggy desktop OS.
  8131. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8132. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8133. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8134. }
  8135. Object.defineProperty(Engine, "LastCreatedEngine", {
  8136. get: function () {
  8137. if (Engine.Instances.length === 0) {
  8138. return null;
  8139. }
  8140. return Engine.Instances[Engine.Instances.length - 1];
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(Engine, "LastCreatedScene", {
  8146. get: function () {
  8147. var lastCreatedEngine = Engine.LastCreatedEngine;
  8148. if (!lastCreatedEngine) {
  8149. return null;
  8150. }
  8151. if (lastCreatedEngine.scenes.length === 0) {
  8152. return null;
  8153. }
  8154. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. /**
  8160. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8161. */
  8162. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8163. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8164. var engine = Engine.Instances[engineIndex];
  8165. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8166. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8167. }
  8168. }
  8169. };
  8170. Object.defineProperty(Engine, "NEVER", {
  8171. get: function () {
  8172. return Engine._NEVER;
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "ALWAYS", {
  8178. get: function () {
  8179. return Engine._ALWAYS;
  8180. },
  8181. enumerable: true,
  8182. configurable: true
  8183. });
  8184. Object.defineProperty(Engine, "LESS", {
  8185. get: function () {
  8186. return Engine._LESS;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "EQUAL", {
  8192. get: function () {
  8193. return Engine._EQUAL;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "LEQUAL", {
  8199. get: function () {
  8200. return Engine._LEQUAL;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "GREATER", {
  8206. get: function () {
  8207. return Engine._GREATER;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "GEQUAL", {
  8213. get: function () {
  8214. return Engine._GEQUAL;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "NOTEQUAL", {
  8220. get: function () {
  8221. return Engine._NOTEQUAL;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "KEEP", {
  8227. get: function () {
  8228. return Engine._KEEP;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "REPLACE", {
  8234. get: function () {
  8235. return Engine._REPLACE;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "INCR", {
  8241. get: function () {
  8242. return Engine._INCR;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "DECR", {
  8248. get: function () {
  8249. return Engine._DECR;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "INVERT", {
  8255. get: function () {
  8256. return Engine._INVERT;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "INCR_WRAP", {
  8262. get: function () {
  8263. return Engine._INCR_WRAP;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "DECR_WRAP", {
  8269. get: function () {
  8270. return Engine._DECR_WRAP;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8276. get: function () {
  8277. return Engine._ALPHA_DISABLE;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8283. get: function () {
  8284. return Engine._ALPHA_ONEONE;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "ALPHA_ADD", {
  8290. get: function () {
  8291. return Engine._ALPHA_ADD;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8297. get: function () {
  8298. return Engine._ALPHA_COMBINE;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8304. get: function () {
  8305. return Engine._ALPHA_SUBTRACT;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8311. get: function () {
  8312. return Engine._ALPHA_MULTIPLY;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8318. get: function () {
  8319. return Engine._ALPHA_MAXIMIZED;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8325. get: function () {
  8326. return Engine._ALPHA_PREMULTIPLIED;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8332. get: function () {
  8333. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8339. get: function () {
  8340. return Engine._ALPHA_INTERPOLATE;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8346. get: function () {
  8347. return Engine._ALPHA_SCREENMODE;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8353. get: function () {
  8354. return Engine._DELAYLOADSTATE_NONE;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8360. get: function () {
  8361. return Engine._DELAYLOADSTATE_LOADED;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8367. get: function () {
  8368. return Engine._DELAYLOADSTATE_LOADING;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8374. get: function () {
  8375. return Engine._DELAYLOADSTATE_NOTLOADED;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8381. get: function () {
  8382. return Engine._TEXTUREFORMAT_ALPHA;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8388. get: function () {
  8389. return Engine._TEXTUREFORMAT_LUMINANCE;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8395. get: function () {
  8396. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8402. get: function () {
  8403. return Engine._TEXTUREFORMAT_RGB;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8409. get: function () {
  8410. return Engine._TEXTUREFORMAT_RGBA;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8416. get: function () {
  8417. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8423. get: function () {
  8424. return Engine._TEXTURETYPE_FLOAT;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8430. get: function () {
  8431. return Engine._TEXTURETYPE_HALF_FLOAT;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8437. get: function () {
  8438. return Engine._SCALEMODE_FLOOR;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8444. get: function () {
  8445. return Engine._SCALEMODE_NEAREST;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8451. get: function () {
  8452. return Engine._SCALEMODE_CEILING;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine, "Version", {
  8458. get: function () {
  8459. return "3.1-beta-1";
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8465. get: function () {
  8466. return this._vrExclusivePointerMode;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8472. get: function () {
  8473. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8479. get: function () {
  8480. return this._webGLVersion < 2 || this.forcePOTTextures;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "badOS", {
  8486. get: function () {
  8487. return this._badOS;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8493. get: function () {
  8494. return this._badDesktopOS;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8500. get: function () {
  8501. return this._performanceMonitor;
  8502. },
  8503. enumerable: true,
  8504. configurable: true
  8505. });
  8506. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8507. get: function () {
  8508. return this._texturesSupported;
  8509. },
  8510. enumerable: true,
  8511. configurable: true
  8512. });
  8513. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8514. get: function () {
  8515. return this._textureFormatInUse;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(Engine.prototype, "currentViewport", {
  8521. get: function () {
  8522. return this._cachedViewport;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8528. // Empty texture
  8529. get: function () {
  8530. if (!this._emptyTexture) {
  8531. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8532. }
  8533. return this._emptyTexture;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8539. get: function () {
  8540. if (!this._emptyTexture3D) {
  8541. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8542. }
  8543. return this._emptyTexture3D;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8549. get: function () {
  8550. if (!this._emptyCubeTexture) {
  8551. var faceData = new Uint8Array(4);
  8552. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8553. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8554. }
  8555. return this._emptyCubeTexture;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Engine.prototype._rebuildInternalTextures = function () {
  8561. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8562. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8563. var internalTexture = currentState_1[_i];
  8564. internalTexture._rebuild();
  8565. }
  8566. };
  8567. Engine.prototype._rebuildEffects = function () {
  8568. for (var key in this._compiledEffects) {
  8569. var effect = this._compiledEffects[key];
  8570. effect._prepareEffect();
  8571. }
  8572. BABYLON.Effect.ResetCache();
  8573. };
  8574. Engine.prototype._rebuildBuffers = function () {
  8575. // Index / Vertex
  8576. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8577. var scene = _a[_i];
  8578. scene.resetCachedMaterial();
  8579. scene._rebuildGeometries();
  8580. scene._rebuildTextures();
  8581. }
  8582. // Uniforms
  8583. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8584. var uniformBuffer = _c[_b];
  8585. uniformBuffer._rebuild();
  8586. }
  8587. };
  8588. Engine.prototype._initGLContext = function () {
  8589. // Caps
  8590. this._caps = new EngineCapabilities();
  8591. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8592. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8593. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8594. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8595. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8596. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8597. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8598. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8599. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8600. // Infos
  8601. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8602. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8603. if (rendererInfo != null) {
  8604. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8605. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8606. }
  8607. if (!this._glVendor) {
  8608. this._glVendor = "Unknown vendor";
  8609. }
  8610. if (!this._glRenderer) {
  8611. this._glRenderer = "Unknown renderer";
  8612. }
  8613. // Constants
  8614. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8615. if (this._gl.RGBA16F !== 0x881A) {
  8616. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8617. }
  8618. if (this._gl.RGBA32F !== 0x8814) {
  8619. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8620. }
  8621. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8622. this._gl.DEPTH24_STENCIL8 = 35056;
  8623. }
  8624. // Extensions
  8625. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8626. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8627. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8628. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8629. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8630. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8631. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8632. 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');
  8633. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8634. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8635. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8636. this._caps.highPrecisionShaderSupported = true;
  8637. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8638. if (this._caps.timerQuery) {
  8639. if (this._webGLVersion === 1) {
  8640. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8641. }
  8642. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8643. }
  8644. // Checks if some of the format renders first to allow the use of webgl inspector.
  8645. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8646. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8647. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8648. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8649. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8650. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8651. if (this._webGLVersion > 1) {
  8652. this._gl.HALF_FLOAT_OES = 0x140B;
  8653. }
  8654. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8655. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8656. // Draw buffers
  8657. if (this._webGLVersion > 1) {
  8658. this._caps.drawBuffersExtension = true;
  8659. }
  8660. else {
  8661. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8662. if (drawBuffersExtension !== null) {
  8663. this._caps.drawBuffersExtension = true;
  8664. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8665. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8666. for (var i = 0; i < 16; i++) {
  8667. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8668. }
  8669. }
  8670. else {
  8671. this._caps.drawBuffersExtension = false;
  8672. }
  8673. }
  8674. // Depth Texture
  8675. if (this._webGLVersion > 1) {
  8676. this._caps.depthTextureExtension = true;
  8677. }
  8678. else {
  8679. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8680. if (depthTextureExtension != null) {
  8681. this._caps.depthTextureExtension = true;
  8682. }
  8683. }
  8684. // Vertex array object
  8685. if (this._webGLVersion > 1) {
  8686. this._caps.vertexArrayObject = true;
  8687. }
  8688. else {
  8689. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8690. if (vertexArrayObjectExtension != null) {
  8691. this._caps.vertexArrayObject = true;
  8692. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8693. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8694. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8695. }
  8696. else {
  8697. this._caps.vertexArrayObject = false;
  8698. }
  8699. }
  8700. // Instances count
  8701. if (this._webGLVersion > 1) {
  8702. this._caps.instancedArrays = true;
  8703. }
  8704. else {
  8705. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8706. if (instanceExtension != null) {
  8707. this._caps.instancedArrays = true;
  8708. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8709. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8710. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8711. }
  8712. else {
  8713. this._caps.instancedArrays = false;
  8714. }
  8715. }
  8716. // Intelligently add supported compressed formats in order to check for.
  8717. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8718. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8719. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8720. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8721. if (this._caps.astc)
  8722. this.texturesSupported.push('-astc.ktx');
  8723. if (this._caps.s3tc)
  8724. this.texturesSupported.push('-dxt.ktx');
  8725. if (this._caps.pvrtc)
  8726. this.texturesSupported.push('-pvrtc.ktx');
  8727. if (this._caps.etc2)
  8728. this.texturesSupported.push('-etc2.ktx');
  8729. if (this._caps.etc1)
  8730. this.texturesSupported.push('-etc1.ktx');
  8731. if (this._gl.getShaderPrecisionFormat) {
  8732. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8733. if (highp) {
  8734. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8735. }
  8736. }
  8737. // Depth buffer
  8738. this.setDepthBuffer(true);
  8739. this.setDepthFunctionToLessOrEqual();
  8740. this.setDepthWrite(true);
  8741. };
  8742. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8743. get: function () {
  8744. return this._webGLVersion;
  8745. },
  8746. enumerable: true,
  8747. configurable: true
  8748. });
  8749. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8750. /**
  8751. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8752. */
  8753. get: function () {
  8754. return this._isStencilEnable;
  8755. },
  8756. enumerable: true,
  8757. configurable: true
  8758. });
  8759. Engine.prototype._prepareWorkingCanvas = function () {
  8760. if (this._workingCanvas) {
  8761. return;
  8762. }
  8763. this._workingCanvas = document.createElement("canvas");
  8764. var context = this._workingCanvas.getContext("2d");
  8765. if (context) {
  8766. this._workingContext = context;
  8767. }
  8768. };
  8769. Engine.prototype.resetTextureCache = function () {
  8770. for (var key in this._activeTexturesCache) {
  8771. this._activeTexturesCache[key] = null;
  8772. }
  8773. };
  8774. Engine.prototype.isDeterministicLockStep = function () {
  8775. return this._deterministicLockstep;
  8776. };
  8777. Engine.prototype.getLockstepMaxSteps = function () {
  8778. return this._lockstepMaxSteps;
  8779. };
  8780. Engine.prototype.getGlInfo = function () {
  8781. return {
  8782. vendor: this._glVendor,
  8783. renderer: this._glRenderer,
  8784. version: this._glVersion
  8785. };
  8786. };
  8787. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8788. if (useScreen === void 0) { useScreen = false; }
  8789. var viewport = camera.viewport;
  8790. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8791. };
  8792. Engine.prototype.getRenderWidth = function (useScreen) {
  8793. if (useScreen === void 0) { useScreen = false; }
  8794. if (!useScreen && this._currentRenderTarget) {
  8795. return this._currentRenderTarget.width;
  8796. }
  8797. return this._gl.drawingBufferWidth;
  8798. };
  8799. Engine.prototype.getRenderHeight = function (useScreen) {
  8800. if (useScreen === void 0) { useScreen = false; }
  8801. if (!useScreen && this._currentRenderTarget) {
  8802. return this._currentRenderTarget.height;
  8803. }
  8804. return this._gl.drawingBufferHeight;
  8805. };
  8806. Engine.prototype.getRenderingCanvas = function () {
  8807. return this._renderingCanvas;
  8808. };
  8809. Engine.prototype.getRenderingCanvasClientRect = function () {
  8810. if (!this._renderingCanvas) {
  8811. return null;
  8812. }
  8813. return this._renderingCanvas.getBoundingClientRect();
  8814. };
  8815. Engine.prototype.setHardwareScalingLevel = function (level) {
  8816. this._hardwareScalingLevel = level;
  8817. this.resize();
  8818. };
  8819. Engine.prototype.getHardwareScalingLevel = function () {
  8820. return this._hardwareScalingLevel;
  8821. };
  8822. Engine.prototype.getLoadedTexturesCache = function () {
  8823. return this._internalTexturesCache;
  8824. };
  8825. Engine.prototype.getCaps = function () {
  8826. return this._caps;
  8827. };
  8828. Object.defineProperty(Engine.prototype, "drawCalls", {
  8829. /** The number of draw calls submitted last frame */
  8830. get: function () {
  8831. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8832. return 0;
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8838. get: function () {
  8839. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8840. return null;
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. Engine.prototype.getDepthFunction = function () {
  8846. return this._depthCullingState.depthFunc;
  8847. };
  8848. Engine.prototype.setDepthFunction = function (depthFunc) {
  8849. this._depthCullingState.depthFunc = depthFunc;
  8850. };
  8851. Engine.prototype.setDepthFunctionToGreater = function () {
  8852. this._depthCullingState.depthFunc = this._gl.GREATER;
  8853. };
  8854. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8855. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8856. };
  8857. Engine.prototype.setDepthFunctionToLess = function () {
  8858. this._depthCullingState.depthFunc = this._gl.LESS;
  8859. };
  8860. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8861. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8862. };
  8863. Engine.prototype.getStencilBuffer = function () {
  8864. return this._stencilState.stencilTest;
  8865. };
  8866. Engine.prototype.setStencilBuffer = function (enable) {
  8867. this._stencilState.stencilTest = enable;
  8868. };
  8869. Engine.prototype.getStencilMask = function () {
  8870. return this._stencilState.stencilMask;
  8871. };
  8872. Engine.prototype.setStencilMask = function (mask) {
  8873. this._stencilState.stencilMask = mask;
  8874. };
  8875. Engine.prototype.getStencilFunction = function () {
  8876. return this._stencilState.stencilFunc;
  8877. };
  8878. Engine.prototype.getStencilFunctionReference = function () {
  8879. return this._stencilState.stencilFuncRef;
  8880. };
  8881. Engine.prototype.getStencilFunctionMask = function () {
  8882. return this._stencilState.stencilFuncMask;
  8883. };
  8884. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8885. this._stencilState.stencilFunc = stencilFunc;
  8886. };
  8887. Engine.prototype.setStencilFunctionReference = function (reference) {
  8888. this._stencilState.stencilFuncRef = reference;
  8889. };
  8890. Engine.prototype.setStencilFunctionMask = function (mask) {
  8891. this._stencilState.stencilFuncMask = mask;
  8892. };
  8893. Engine.prototype.getStencilOperationFail = function () {
  8894. return this._stencilState.stencilOpStencilFail;
  8895. };
  8896. Engine.prototype.getStencilOperationDepthFail = function () {
  8897. return this._stencilState.stencilOpDepthFail;
  8898. };
  8899. Engine.prototype.getStencilOperationPass = function () {
  8900. return this._stencilState.stencilOpStencilDepthPass;
  8901. };
  8902. Engine.prototype.setStencilOperationFail = function (operation) {
  8903. this._stencilState.stencilOpStencilFail = operation;
  8904. };
  8905. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8906. this._stencilState.stencilOpDepthFail = operation;
  8907. };
  8908. Engine.prototype.setStencilOperationPass = function (operation) {
  8909. this._stencilState.stencilOpStencilDepthPass = operation;
  8910. };
  8911. Engine.prototype.setDitheringState = function (value) {
  8912. if (value) {
  8913. this._gl.enable(this._gl.DITHER);
  8914. }
  8915. else {
  8916. this._gl.disable(this._gl.DITHER);
  8917. }
  8918. };
  8919. Engine.prototype.setRasterizerState = function (value) {
  8920. if (value) {
  8921. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8922. }
  8923. else {
  8924. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8925. }
  8926. };
  8927. /**
  8928. * stop executing a render loop function and remove it from the execution array
  8929. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8930. */
  8931. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8932. if (!renderFunction) {
  8933. this._activeRenderLoops = [];
  8934. return;
  8935. }
  8936. var index = this._activeRenderLoops.indexOf(renderFunction);
  8937. if (index >= 0) {
  8938. this._activeRenderLoops.splice(index, 1);
  8939. }
  8940. };
  8941. Engine.prototype._renderLoop = function () {
  8942. if (!this._contextWasLost) {
  8943. var shouldRender = true;
  8944. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8945. shouldRender = false;
  8946. }
  8947. if (shouldRender) {
  8948. // Start new frame
  8949. this.beginFrame();
  8950. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8951. var renderFunction = this._activeRenderLoops[index];
  8952. renderFunction();
  8953. }
  8954. // Present
  8955. this.endFrame();
  8956. }
  8957. }
  8958. if (this._activeRenderLoops.length > 0) {
  8959. // Register new frame
  8960. var requester = null;
  8961. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8962. requester = this._vrDisplay;
  8963. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8964. }
  8965. else {
  8966. this._renderingQueueLaunched = false;
  8967. }
  8968. };
  8969. /**
  8970. * Register and execute a render loop. The engine can have more than one render function.
  8971. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8972. * @example
  8973. * engine.runRenderLoop(function () {
  8974. * scene.render()
  8975. * })
  8976. */
  8977. Engine.prototype.runRenderLoop = function (renderFunction) {
  8978. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8979. return;
  8980. }
  8981. this._activeRenderLoops.push(renderFunction);
  8982. if (!this._renderingQueueLaunched) {
  8983. this._renderingQueueLaunched = true;
  8984. this._bindedRenderFunction = this._renderLoop.bind(this);
  8985. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8986. }
  8987. };
  8988. /**
  8989. * Toggle full screen mode.
  8990. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8991. * @param {any} options - an options object to be sent to the requestFullscreen function
  8992. */
  8993. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8994. if (this.isFullscreen) {
  8995. BABYLON.Tools.ExitFullscreen();
  8996. }
  8997. else {
  8998. this._pointerLockRequested = requestPointerLock;
  8999. if (this._renderingCanvas) {
  9000. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9001. }
  9002. }
  9003. };
  9004. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9005. if (stencil === void 0) { stencil = false; }
  9006. this.applyStates();
  9007. var mode = 0;
  9008. if (backBuffer && color) {
  9009. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9010. mode |= this._gl.COLOR_BUFFER_BIT;
  9011. }
  9012. if (depth) {
  9013. this._gl.clearDepth(1.0);
  9014. mode |= this._gl.DEPTH_BUFFER_BIT;
  9015. }
  9016. if (stencil) {
  9017. this._gl.clearStencil(0);
  9018. mode |= this._gl.STENCIL_BUFFER_BIT;
  9019. }
  9020. this._gl.clear(mode);
  9021. };
  9022. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9023. var gl = this._gl;
  9024. // Save state
  9025. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9026. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9027. // Change state
  9028. gl.enable(gl.SCISSOR_TEST);
  9029. gl.scissor(x, y, width, height);
  9030. // Clear
  9031. this.clear(clearColor, true, true, true);
  9032. // Restore state
  9033. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9034. if (curScissor === true) {
  9035. gl.enable(gl.SCISSOR_TEST);
  9036. }
  9037. else {
  9038. gl.disable(gl.SCISSOR_TEST);
  9039. }
  9040. };
  9041. /**
  9042. * Set the WebGL's viewport
  9043. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9044. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9045. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9046. */
  9047. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9048. var width = requiredWidth || this.getRenderWidth();
  9049. var height = requiredHeight || this.getRenderHeight();
  9050. var x = viewport.x || 0;
  9051. var y = viewport.y || 0;
  9052. this._cachedViewport = viewport;
  9053. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9054. };
  9055. /**
  9056. * Directly set the WebGL Viewport
  9057. * The x, y, width & height are directly passed to the WebGL call
  9058. * @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.
  9059. */
  9060. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9061. var currentViewport = this._cachedViewport;
  9062. this._cachedViewport = null;
  9063. this._gl.viewport(x, y, width, height);
  9064. return currentViewport;
  9065. };
  9066. Engine.prototype.beginFrame = function () {
  9067. this.onBeginFrameObservable.notifyObservers(this);
  9068. this._measureFps();
  9069. };
  9070. Engine.prototype.endFrame = function () {
  9071. //force a flush in case we are using a bad OS.
  9072. if (this._badOS) {
  9073. this.flushFramebuffer();
  9074. }
  9075. //submit frame to the vr device, if enabled
  9076. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9077. // TODO: We should only submit the frame if we read frameData successfully.
  9078. this._vrDisplay.submitFrame();
  9079. }
  9080. this.onEndFrameObservable.notifyObservers(this);
  9081. };
  9082. /**
  9083. * resize the view according to the canvas' size.
  9084. * @example
  9085. * window.addEventListener("resize", function () {
  9086. * engine.resize();
  9087. * });
  9088. */
  9089. Engine.prototype.resize = function () {
  9090. // We're not resizing the size of the canvas while in VR mode & presenting
  9091. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9092. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9093. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9094. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9095. }
  9096. };
  9097. /**
  9098. * force a specific size of the canvas
  9099. * @param {number} width - the new canvas' width
  9100. * @param {number} height - the new canvas' height
  9101. */
  9102. Engine.prototype.setSize = function (width, height) {
  9103. if (!this._renderingCanvas) {
  9104. return;
  9105. }
  9106. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9107. return;
  9108. }
  9109. this._renderingCanvas.width = width;
  9110. this._renderingCanvas.height = height;
  9111. for (var index = 0; index < this.scenes.length; index++) {
  9112. var scene = this.scenes[index];
  9113. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9114. var cam = scene.cameras[camIndex];
  9115. cam._currentRenderId = 0;
  9116. }
  9117. }
  9118. if (this.onResizeObservable.hasObservers) {
  9119. this.onResizeObservable.notifyObservers(this);
  9120. }
  9121. };
  9122. // WebVR functions
  9123. Engine.prototype.isVRDevicePresent = function () {
  9124. return !!this._vrDisplay;
  9125. };
  9126. Engine.prototype.getVRDevice = function () {
  9127. return this._vrDisplay;
  9128. };
  9129. Engine.prototype.initWebVR = function () {
  9130. var _this = this;
  9131. var notifyObservers = function () {
  9132. var eventArgs = {
  9133. vrDisplay: _this._vrDisplay,
  9134. vrSupported: _this._vrSupported
  9135. };
  9136. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9137. };
  9138. if (!this._onVrDisplayConnect) {
  9139. this._onVrDisplayConnect = function (event) {
  9140. _this._vrDisplay = event.display;
  9141. notifyObservers();
  9142. };
  9143. this._onVrDisplayDisconnect = function () {
  9144. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9145. _this._vrDisplay = undefined;
  9146. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9147. notifyObservers();
  9148. };
  9149. this._onVrDisplayPresentChange = function () {
  9150. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9151. };
  9152. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9153. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9154. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9155. }
  9156. this._getVRDisplays(notifyObservers);
  9157. return this.onVRDisplayChangedObservable;
  9158. };
  9159. Engine.prototype.enableVR = function () {
  9160. var _this = this;
  9161. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9162. var onResolved = function () {
  9163. _this.onVRRequestPresentComplete.notifyObservers(true);
  9164. _this._onVRFullScreenTriggered();
  9165. };
  9166. var onRejected = function () {
  9167. _this.onVRRequestPresentComplete.notifyObservers(false);
  9168. };
  9169. this.onVRRequestPresentStart.notifyObservers(this);
  9170. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9171. }
  9172. };
  9173. Engine.prototype.disableVR = function () {
  9174. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9175. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9176. }
  9177. };
  9178. Engine.prototype._getVRDisplays = function (callback) {
  9179. var _this = this;
  9180. var getWebVRDevices = function (devices) {
  9181. _this._vrSupported = true;
  9182. // note that devices may actually be an empty array. This is fine;
  9183. // we expect this._vrDisplay to be undefined in this case.
  9184. return _this._vrDisplay = devices[0];
  9185. };
  9186. if (navigator.getVRDisplays) {
  9187. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9188. // TODO: System CANNOT support WebVR, despite API presence.
  9189. _this._vrSupported = false;
  9190. callback();
  9191. });
  9192. }
  9193. else {
  9194. // TODO: Browser does not support WebVR
  9195. this._vrDisplay = undefined;
  9196. this._vrSupported = false;
  9197. callback();
  9198. }
  9199. };
  9200. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9201. if (this._currentRenderTarget) {
  9202. this.unBindFramebuffer(this._currentRenderTarget);
  9203. }
  9204. this._currentRenderTarget = texture;
  9205. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9206. var gl = this._gl;
  9207. if (texture.isCube) {
  9208. if (faceIndex === undefined) {
  9209. faceIndex = 0;
  9210. }
  9211. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9212. }
  9213. if (this._cachedViewport && !forceFullscreenViewport) {
  9214. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9215. }
  9216. else {
  9217. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9218. }
  9219. this.wipeCaches();
  9220. };
  9221. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9222. if (this._currentFramebuffer !== framebuffer) {
  9223. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9224. this._currentFramebuffer = framebuffer;
  9225. }
  9226. };
  9227. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9228. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9229. this._currentRenderTarget = null;
  9230. // If MSAA, we need to bitblt back to main texture
  9231. var gl = this._gl;
  9232. if (texture._MSAAFramebuffer) {
  9233. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9234. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9235. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9236. }
  9237. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9238. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9239. gl.generateMipmap(gl.TEXTURE_2D);
  9240. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9241. }
  9242. if (onBeforeUnbind) {
  9243. if (texture._MSAAFramebuffer) {
  9244. // Bind the correct framebuffer
  9245. this.bindUnboundFramebuffer(texture._framebuffer);
  9246. }
  9247. onBeforeUnbind();
  9248. }
  9249. this.bindUnboundFramebuffer(null);
  9250. };
  9251. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9252. if (texture.generateMipMaps) {
  9253. var gl = this._gl;
  9254. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9255. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9257. }
  9258. };
  9259. Engine.prototype.flushFramebuffer = function () {
  9260. this._gl.flush();
  9261. };
  9262. Engine.prototype.restoreDefaultFramebuffer = function () {
  9263. if (this._currentRenderTarget) {
  9264. this.unBindFramebuffer(this._currentRenderTarget);
  9265. }
  9266. else {
  9267. this.bindUnboundFramebuffer(null);
  9268. }
  9269. if (this._cachedViewport) {
  9270. this.setViewport(this._cachedViewport);
  9271. }
  9272. this.wipeCaches();
  9273. };
  9274. // UBOs
  9275. Engine.prototype.createUniformBuffer = function (elements) {
  9276. var ubo = this._gl.createBuffer();
  9277. if (!ubo) {
  9278. throw new Error("Unable to create uniform buffer");
  9279. }
  9280. this.bindUniformBuffer(ubo);
  9281. if (elements instanceof Float32Array) {
  9282. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9283. }
  9284. else {
  9285. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9286. }
  9287. this.bindUniformBuffer(null);
  9288. ubo.references = 1;
  9289. return ubo;
  9290. };
  9291. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9292. var ubo = this._gl.createBuffer();
  9293. if (!ubo) {
  9294. throw new Error("Unable to create dynamic uniform buffer");
  9295. }
  9296. this.bindUniformBuffer(ubo);
  9297. if (elements instanceof Float32Array) {
  9298. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9299. }
  9300. else {
  9301. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9302. }
  9303. this.bindUniformBuffer(null);
  9304. ubo.references = 1;
  9305. return ubo;
  9306. };
  9307. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9308. this.bindUniformBuffer(uniformBuffer);
  9309. if (offset === undefined) {
  9310. offset = 0;
  9311. }
  9312. if (count === undefined) {
  9313. if (elements instanceof Float32Array) {
  9314. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9315. }
  9316. else {
  9317. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9318. }
  9319. }
  9320. else {
  9321. if (elements instanceof Float32Array) {
  9322. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9323. }
  9324. else {
  9325. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9326. }
  9327. }
  9328. this.bindUniformBuffer(null);
  9329. };
  9330. // VBOs
  9331. Engine.prototype._resetVertexBufferBinding = function () {
  9332. this.bindArrayBuffer(null);
  9333. this._cachedVertexBuffers = null;
  9334. };
  9335. Engine.prototype.createVertexBuffer = function (vertices) {
  9336. var vbo = this._gl.createBuffer();
  9337. if (!vbo) {
  9338. throw new Error("Unable to create vertex buffer");
  9339. }
  9340. this.bindArrayBuffer(vbo);
  9341. if (vertices instanceof Float32Array) {
  9342. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9343. }
  9344. else {
  9345. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9346. }
  9347. this._resetVertexBufferBinding();
  9348. vbo.references = 1;
  9349. return vbo;
  9350. };
  9351. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9352. var vbo = this._gl.createBuffer();
  9353. if (!vbo) {
  9354. throw new Error("Unable to create dynamic vertex buffer");
  9355. }
  9356. this.bindArrayBuffer(vbo);
  9357. if (vertices instanceof Float32Array) {
  9358. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9359. }
  9360. else {
  9361. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9362. }
  9363. this._resetVertexBufferBinding();
  9364. vbo.references = 1;
  9365. return vbo;
  9366. };
  9367. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9368. if (offset === void 0) { offset = 0; }
  9369. // Force cache update
  9370. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9371. this.bindIndexBuffer(indexBuffer);
  9372. var arrayBuffer;
  9373. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9374. arrayBuffer = indices;
  9375. }
  9376. else {
  9377. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9378. }
  9379. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9380. this._resetIndexBufferBinding();
  9381. };
  9382. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9383. this.bindArrayBuffer(vertexBuffer);
  9384. if (offset === undefined) {
  9385. offset = 0;
  9386. }
  9387. if (count === undefined) {
  9388. if (vertices instanceof Float32Array) {
  9389. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9390. }
  9391. else {
  9392. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9393. }
  9394. }
  9395. else {
  9396. if (vertices instanceof Float32Array) {
  9397. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9398. }
  9399. else {
  9400. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9401. }
  9402. }
  9403. this._resetVertexBufferBinding();
  9404. };
  9405. Engine.prototype._resetIndexBufferBinding = function () {
  9406. this.bindIndexBuffer(null);
  9407. this._cachedIndexBuffer = null;
  9408. };
  9409. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9410. var vbo = this._gl.createBuffer();
  9411. if (!vbo) {
  9412. throw new Error("Unable to create index buffer");
  9413. }
  9414. this.bindIndexBuffer(vbo);
  9415. // Check for 32 bits indices
  9416. var arrayBuffer;
  9417. var need32Bits = false;
  9418. if (indices instanceof Uint16Array) {
  9419. arrayBuffer = indices;
  9420. }
  9421. else {
  9422. //check 32 bit support
  9423. if (this._caps.uintIndices) {
  9424. if (indices instanceof Uint32Array) {
  9425. arrayBuffer = indices;
  9426. need32Bits = true;
  9427. }
  9428. else {
  9429. //number[] or Int32Array, check if 32 bit is necessary
  9430. for (var index = 0; index < indices.length; index++) {
  9431. if (indices[index] > 65535) {
  9432. need32Bits = true;
  9433. break;
  9434. }
  9435. }
  9436. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9437. }
  9438. }
  9439. else {
  9440. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9441. arrayBuffer = new Uint16Array(indices);
  9442. }
  9443. }
  9444. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9445. this._resetIndexBufferBinding();
  9446. vbo.references = 1;
  9447. vbo.is32Bits = need32Bits;
  9448. return vbo;
  9449. };
  9450. Engine.prototype.bindArrayBuffer = function (buffer) {
  9451. if (!this._vaoRecordInProgress) {
  9452. this._unbindVertexArrayObject();
  9453. }
  9454. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9455. };
  9456. Engine.prototype.bindUniformBuffer = function (buffer) {
  9457. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9458. };
  9459. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9460. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9461. };
  9462. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9463. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9464. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9465. };
  9466. ;
  9467. Engine.prototype.bindIndexBuffer = function (buffer) {
  9468. if (!this._vaoRecordInProgress) {
  9469. this._unbindVertexArrayObject();
  9470. }
  9471. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9472. };
  9473. Engine.prototype.bindBuffer = function (buffer, target) {
  9474. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9475. this._gl.bindBuffer(target, buffer);
  9476. this._currentBoundBuffer[target] = buffer;
  9477. }
  9478. };
  9479. Engine.prototype.updateArrayBuffer = function (data) {
  9480. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9481. };
  9482. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9483. var pointer = this._currentBufferPointers[indx];
  9484. var changed = false;
  9485. if (!pointer.active) {
  9486. changed = true;
  9487. pointer.active = true;
  9488. pointer.index = indx;
  9489. pointer.size = size;
  9490. pointer.type = type;
  9491. pointer.normalized = normalized;
  9492. pointer.stride = stride;
  9493. pointer.offset = offset;
  9494. pointer.buffer = buffer;
  9495. }
  9496. else {
  9497. if (pointer.buffer !== buffer) {
  9498. pointer.buffer = buffer;
  9499. changed = true;
  9500. }
  9501. if (pointer.size !== size) {
  9502. pointer.size = size;
  9503. changed = true;
  9504. }
  9505. if (pointer.type !== type) {
  9506. pointer.type = type;
  9507. changed = true;
  9508. }
  9509. if (pointer.normalized !== normalized) {
  9510. pointer.normalized = normalized;
  9511. changed = true;
  9512. }
  9513. if (pointer.stride !== stride) {
  9514. pointer.stride = stride;
  9515. changed = true;
  9516. }
  9517. if (pointer.offset !== offset) {
  9518. pointer.offset = offset;
  9519. changed = true;
  9520. }
  9521. }
  9522. if (changed || this._vaoRecordInProgress) {
  9523. this.bindArrayBuffer(buffer);
  9524. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9525. }
  9526. };
  9527. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9528. if (indexBuffer == null) {
  9529. return;
  9530. }
  9531. if (this._cachedIndexBuffer !== indexBuffer) {
  9532. this._cachedIndexBuffer = indexBuffer;
  9533. this.bindIndexBuffer(indexBuffer);
  9534. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9535. }
  9536. };
  9537. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9538. var attributes = effect.getAttributesNames();
  9539. if (!this._vaoRecordInProgress) {
  9540. this._unbindVertexArrayObject();
  9541. }
  9542. this.unbindAllAttributes();
  9543. for (var index = 0; index < attributes.length; index++) {
  9544. var order = effect.getAttributeLocation(index);
  9545. if (order >= 0) {
  9546. var vertexBuffer = vertexBuffers[attributes[index]];
  9547. if (!vertexBuffer) {
  9548. continue;
  9549. }
  9550. this._gl.enableVertexAttribArray(order);
  9551. if (!this._vaoRecordInProgress) {
  9552. this._vertexAttribArraysEnabled[order] = true;
  9553. }
  9554. var buffer = vertexBuffer.getBuffer();
  9555. if (buffer) {
  9556. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9557. if (vertexBuffer.getIsInstanced()) {
  9558. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9559. if (!this._vaoRecordInProgress) {
  9560. this._currentInstanceLocations.push(order);
  9561. this._currentInstanceBuffers.push(buffer);
  9562. }
  9563. }
  9564. }
  9565. }
  9566. }
  9567. };
  9568. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9569. var vao = this._gl.createVertexArray();
  9570. this._vaoRecordInProgress = true;
  9571. this._gl.bindVertexArray(vao);
  9572. this._mustWipeVertexAttributes = true;
  9573. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9574. this.bindIndexBuffer(indexBuffer);
  9575. this._vaoRecordInProgress = false;
  9576. this._gl.bindVertexArray(null);
  9577. return vao;
  9578. };
  9579. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9580. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9581. this._cachedVertexArrayObject = vertexArrayObject;
  9582. this._gl.bindVertexArray(vertexArrayObject);
  9583. this._cachedVertexBuffers = null;
  9584. this._cachedIndexBuffer = null;
  9585. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9586. this._mustWipeVertexAttributes = true;
  9587. }
  9588. };
  9589. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9590. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9591. this._cachedVertexBuffers = vertexBuffer;
  9592. this._cachedEffectForVertexBuffers = effect;
  9593. var attributesCount = effect.getAttributesCount();
  9594. this._unbindVertexArrayObject();
  9595. this.unbindAllAttributes();
  9596. var offset = 0;
  9597. for (var index = 0; index < attributesCount; index++) {
  9598. if (index < vertexDeclaration.length) {
  9599. var order = effect.getAttributeLocation(index);
  9600. if (order >= 0) {
  9601. this._gl.enableVertexAttribArray(order);
  9602. this._vertexAttribArraysEnabled[order] = true;
  9603. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9604. }
  9605. offset += vertexDeclaration[index] * 4;
  9606. }
  9607. }
  9608. }
  9609. this._bindIndexBufferWithCache(indexBuffer);
  9610. };
  9611. Engine.prototype._unbindVertexArrayObject = function () {
  9612. if (!this._cachedVertexArrayObject) {
  9613. return;
  9614. }
  9615. this._cachedVertexArrayObject = null;
  9616. this._gl.bindVertexArray(null);
  9617. };
  9618. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9619. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9620. this._cachedVertexBuffers = vertexBuffers;
  9621. this._cachedEffectForVertexBuffers = effect;
  9622. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9623. }
  9624. this._bindIndexBufferWithCache(indexBuffer);
  9625. };
  9626. Engine.prototype.unbindInstanceAttributes = function () {
  9627. var boundBuffer;
  9628. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9629. var instancesBuffer = this._currentInstanceBuffers[i];
  9630. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9631. boundBuffer = instancesBuffer;
  9632. this.bindArrayBuffer(instancesBuffer);
  9633. }
  9634. var offsetLocation = this._currentInstanceLocations[i];
  9635. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9636. }
  9637. this._currentInstanceBuffers.length = 0;
  9638. this._currentInstanceLocations.length = 0;
  9639. };
  9640. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9641. this._gl.deleteVertexArray(vao);
  9642. };
  9643. Engine.prototype._releaseBuffer = function (buffer) {
  9644. buffer.references--;
  9645. if (buffer.references === 0) {
  9646. this._gl.deleteBuffer(buffer);
  9647. return true;
  9648. }
  9649. return false;
  9650. };
  9651. Engine.prototype.createInstancesBuffer = function (capacity) {
  9652. var buffer = this._gl.createBuffer();
  9653. if (!buffer) {
  9654. throw new Error("Unable to create instance buffer");
  9655. }
  9656. buffer.capacity = capacity;
  9657. this.bindArrayBuffer(buffer);
  9658. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9659. return buffer;
  9660. };
  9661. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9662. this._gl.deleteBuffer(buffer);
  9663. };
  9664. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9665. this.bindArrayBuffer(instancesBuffer);
  9666. if (data) {
  9667. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9668. }
  9669. if (offsetLocations[0].index !== undefined) {
  9670. var stride = 0;
  9671. for (var i = 0; i < offsetLocations.length; i++) {
  9672. var ai = offsetLocations[i];
  9673. stride += ai.attributeSize * 4;
  9674. }
  9675. for (var i = 0; i < offsetLocations.length; i++) {
  9676. var ai = offsetLocations[i];
  9677. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9678. this._gl.enableVertexAttribArray(ai.index);
  9679. this._vertexAttribArraysEnabled[ai.index] = true;
  9680. }
  9681. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9682. this._gl.vertexAttribDivisor(ai.index, 1);
  9683. this._currentInstanceLocations.push(ai.index);
  9684. this._currentInstanceBuffers.push(instancesBuffer);
  9685. }
  9686. }
  9687. else {
  9688. for (var index = 0; index < 4; index++) {
  9689. var offsetLocation = offsetLocations[index];
  9690. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9691. this._gl.enableVertexAttribArray(offsetLocation);
  9692. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9693. }
  9694. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9695. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9696. this._currentInstanceLocations.push(offsetLocation);
  9697. this._currentInstanceBuffers.push(instancesBuffer);
  9698. }
  9699. }
  9700. };
  9701. Engine.prototype.applyStates = function () {
  9702. this._depthCullingState.apply(this._gl);
  9703. this._stencilState.apply(this._gl);
  9704. this._alphaState.apply(this._gl);
  9705. };
  9706. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9707. // Apply states
  9708. this.applyStates();
  9709. this._drawCalls.addCount(1, false);
  9710. // Render
  9711. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9712. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9713. if (instancesCount) {
  9714. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9715. return;
  9716. }
  9717. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9718. };
  9719. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9720. // Apply states
  9721. this.applyStates();
  9722. this._drawCalls.addCount(1, false);
  9723. if (instancesCount) {
  9724. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9725. return;
  9726. }
  9727. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9728. };
  9729. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9730. // Apply states
  9731. this.applyStates();
  9732. this._drawCalls.addCount(1, false);
  9733. if (instancesCount) {
  9734. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9735. return;
  9736. }
  9737. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9738. };
  9739. // Shaders
  9740. Engine.prototype._releaseEffect = function (effect) {
  9741. if (this._compiledEffects[effect._key]) {
  9742. delete this._compiledEffects[effect._key];
  9743. this._deleteProgram(effect.getProgram());
  9744. }
  9745. };
  9746. Engine.prototype._deleteProgram = function (program) {
  9747. if (program) {
  9748. program.__SPECTOR_rebuildProgram = null;
  9749. if (program.transformFeedback) {
  9750. this.deleteTransformFeedback(program.transformFeedback);
  9751. program.transformFeedback = null;
  9752. }
  9753. this._gl.deleteProgram(program);
  9754. }
  9755. };
  9756. /**
  9757. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9758. * @param samplers An array of string used to represent textures
  9759. */
  9760. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9761. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9762. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9763. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9764. if (this._compiledEffects[name]) {
  9765. var compiledEffect = this._compiledEffects[name];
  9766. if (onCompiled && compiledEffect.isReady()) {
  9767. onCompiled(compiledEffect);
  9768. }
  9769. return compiledEffect;
  9770. }
  9771. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9772. effect._key = name;
  9773. this._compiledEffects[name] = effect;
  9774. return effect;
  9775. };
  9776. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9777. if (uniformsNames === void 0) { uniformsNames = []; }
  9778. if (samplers === void 0) { samplers = []; }
  9779. if (defines === void 0) { defines = ""; }
  9780. return this.createEffect({
  9781. vertex: "particles",
  9782. fragmentElement: fragmentName
  9783. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9784. };
  9785. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9786. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9787. context = context || this._gl;
  9788. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9789. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9790. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9791. };
  9792. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9793. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9794. context = context || this._gl;
  9795. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9796. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9797. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9798. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9799. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9800. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9801. return program;
  9802. };
  9803. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9804. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9805. var shaderProgram = context.createProgram();
  9806. if (!shaderProgram) {
  9807. throw new Error("Unable to create program");
  9808. }
  9809. context.attachShader(shaderProgram, vertexShader);
  9810. context.attachShader(shaderProgram, fragmentShader);
  9811. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9812. var transformFeedback = this.createTransformFeedback();
  9813. this.bindTransformFeedback(transformFeedback);
  9814. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9815. shaderProgram.transformFeedback = transformFeedback;
  9816. }
  9817. context.linkProgram(shaderProgram);
  9818. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9819. this.bindTransformFeedback(null);
  9820. }
  9821. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9822. if (!linked) {
  9823. context.validateProgram(shaderProgram);
  9824. var error = context.getProgramInfoLog(shaderProgram);
  9825. if (error) {
  9826. throw new Error(error);
  9827. }
  9828. }
  9829. context.deleteShader(vertexShader);
  9830. context.deleteShader(fragmentShader);
  9831. return shaderProgram;
  9832. };
  9833. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9834. var results = new Array();
  9835. for (var index = 0; index < uniformsNames.length; index++) {
  9836. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9837. }
  9838. return results;
  9839. };
  9840. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9841. var results = [];
  9842. for (var index = 0; index < attributesNames.length; index++) {
  9843. try {
  9844. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9845. }
  9846. catch (e) {
  9847. results.push(-1);
  9848. }
  9849. }
  9850. return results;
  9851. };
  9852. Engine.prototype.enableEffect = function (effect) {
  9853. if (!effect) {
  9854. return;
  9855. }
  9856. // Use program
  9857. this.setProgram(effect.getProgram());
  9858. this._currentEffect = effect;
  9859. if (effect.onBind) {
  9860. effect.onBind(effect);
  9861. }
  9862. effect.onBindObservable.notifyObservers(effect);
  9863. };
  9864. Engine.prototype.setIntArray = function (uniform, array) {
  9865. if (!uniform)
  9866. return;
  9867. this._gl.uniform1iv(uniform, array);
  9868. };
  9869. Engine.prototype.setIntArray2 = function (uniform, array) {
  9870. if (!uniform || array.length % 2 !== 0)
  9871. return;
  9872. this._gl.uniform2iv(uniform, array);
  9873. };
  9874. Engine.prototype.setIntArray3 = function (uniform, array) {
  9875. if (!uniform || array.length % 3 !== 0)
  9876. return;
  9877. this._gl.uniform3iv(uniform, array);
  9878. };
  9879. Engine.prototype.setIntArray4 = function (uniform, array) {
  9880. if (!uniform || array.length % 4 !== 0)
  9881. return;
  9882. this._gl.uniform4iv(uniform, array);
  9883. };
  9884. Engine.prototype.setFloatArray = function (uniform, array) {
  9885. if (!uniform)
  9886. return;
  9887. this._gl.uniform1fv(uniform, array);
  9888. };
  9889. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9890. if (!uniform || array.length % 2 !== 0)
  9891. return;
  9892. this._gl.uniform2fv(uniform, array);
  9893. };
  9894. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9895. if (!uniform || array.length % 3 !== 0)
  9896. return;
  9897. this._gl.uniform3fv(uniform, array);
  9898. };
  9899. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9900. if (!uniform || array.length % 4 !== 0)
  9901. return;
  9902. this._gl.uniform4fv(uniform, array);
  9903. };
  9904. Engine.prototype.setArray = function (uniform, array) {
  9905. if (!uniform)
  9906. return;
  9907. this._gl.uniform1fv(uniform, array);
  9908. };
  9909. Engine.prototype.setArray2 = function (uniform, array) {
  9910. if (!uniform || array.length % 2 !== 0)
  9911. return;
  9912. this._gl.uniform2fv(uniform, array);
  9913. };
  9914. Engine.prototype.setArray3 = function (uniform, array) {
  9915. if (!uniform || array.length % 3 !== 0)
  9916. return;
  9917. this._gl.uniform3fv(uniform, array);
  9918. };
  9919. Engine.prototype.setArray4 = function (uniform, array) {
  9920. if (!uniform || array.length % 4 !== 0)
  9921. return;
  9922. this._gl.uniform4fv(uniform, array);
  9923. };
  9924. Engine.prototype.setMatrices = function (uniform, matrices) {
  9925. if (!uniform)
  9926. return;
  9927. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9928. };
  9929. Engine.prototype.setMatrix = function (uniform, matrix) {
  9930. if (!uniform)
  9931. return;
  9932. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9933. };
  9934. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9935. if (!uniform)
  9936. return;
  9937. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9938. };
  9939. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9940. if (!uniform)
  9941. return;
  9942. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9943. };
  9944. Engine.prototype.setFloat = function (uniform, value) {
  9945. if (!uniform)
  9946. return;
  9947. this._gl.uniform1f(uniform, value);
  9948. };
  9949. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9950. if (!uniform)
  9951. return;
  9952. this._gl.uniform2f(uniform, x, y);
  9953. };
  9954. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9955. if (!uniform)
  9956. return;
  9957. this._gl.uniform3f(uniform, x, y, z);
  9958. };
  9959. Engine.prototype.setBool = function (uniform, bool) {
  9960. if (!uniform)
  9961. return;
  9962. this._gl.uniform1i(uniform, bool);
  9963. };
  9964. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9965. if (!uniform)
  9966. return;
  9967. this._gl.uniform4f(uniform, x, y, z, w);
  9968. };
  9969. Engine.prototype.setColor3 = function (uniform, color3) {
  9970. if (!uniform)
  9971. return;
  9972. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9973. };
  9974. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9975. if (!uniform)
  9976. return;
  9977. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9978. };
  9979. // States
  9980. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9981. if (zOffset === void 0) { zOffset = 0; }
  9982. if (reverseSide === void 0) { reverseSide = false; }
  9983. // Culling
  9984. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9985. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9986. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9987. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9988. if (culling) {
  9989. this._depthCullingState.cullFace = cullFace;
  9990. this._depthCullingState.cull = true;
  9991. }
  9992. else {
  9993. this._depthCullingState.cull = false;
  9994. }
  9995. }
  9996. // Z offset
  9997. this.setZOffset(zOffset);
  9998. };
  9999. Engine.prototype.setZOffset = function (value) {
  10000. this._depthCullingState.zOffset = value;
  10001. };
  10002. Engine.prototype.getZOffset = function () {
  10003. return this._depthCullingState.zOffset;
  10004. };
  10005. Engine.prototype.setDepthBuffer = function (enable) {
  10006. this._depthCullingState.depthTest = enable;
  10007. };
  10008. Engine.prototype.getDepthWrite = function () {
  10009. return this._depthCullingState.depthMask;
  10010. };
  10011. Engine.prototype.setDepthWrite = function (enable) {
  10012. this._depthCullingState.depthMask = enable;
  10013. };
  10014. Engine.prototype.setColorWrite = function (enable) {
  10015. this._gl.colorMask(enable, enable, enable, enable);
  10016. this._colorWrite = enable;
  10017. };
  10018. Engine.prototype.getColorWrite = function () {
  10019. return this._colorWrite;
  10020. };
  10021. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10022. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10023. };
  10024. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10025. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10026. if (this._alphaMode === mode) {
  10027. return;
  10028. }
  10029. switch (mode) {
  10030. case Engine.ALPHA_DISABLE:
  10031. this._alphaState.alphaBlend = false;
  10032. break;
  10033. case Engine.ALPHA_PREMULTIPLIED:
  10034. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10035. this._alphaState.alphaBlend = true;
  10036. break;
  10037. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10038. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10039. this._alphaState.alphaBlend = true;
  10040. break;
  10041. case Engine.ALPHA_COMBINE:
  10042. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10043. this._alphaState.alphaBlend = true;
  10044. break;
  10045. case Engine.ALPHA_ONEONE:
  10046. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10047. this._alphaState.alphaBlend = true;
  10048. break;
  10049. case Engine.ALPHA_ADD:
  10050. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10051. this._alphaState.alphaBlend = true;
  10052. break;
  10053. case Engine.ALPHA_SUBTRACT:
  10054. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10055. this._alphaState.alphaBlend = true;
  10056. break;
  10057. case Engine.ALPHA_MULTIPLY:
  10058. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10059. this._alphaState.alphaBlend = true;
  10060. break;
  10061. case Engine.ALPHA_MAXIMIZED:
  10062. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10063. this._alphaState.alphaBlend = true;
  10064. break;
  10065. case Engine.ALPHA_INTERPOLATE:
  10066. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10067. this._alphaState.alphaBlend = true;
  10068. break;
  10069. case Engine.ALPHA_SCREENMODE:
  10070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10071. this._alphaState.alphaBlend = true;
  10072. break;
  10073. }
  10074. if (!noDepthWriteChange) {
  10075. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10076. }
  10077. this._alphaMode = mode;
  10078. };
  10079. Engine.prototype.getAlphaMode = function () {
  10080. return this._alphaMode;
  10081. };
  10082. Engine.prototype.setAlphaTesting = function (enable) {
  10083. this._alphaTest = enable;
  10084. };
  10085. Engine.prototype.getAlphaTesting = function () {
  10086. return !!this._alphaTest;
  10087. };
  10088. // Textures
  10089. Engine.prototype.wipeCaches = function (bruteForce) {
  10090. if (this.preventCacheWipeBetweenFrames) {
  10091. return;
  10092. }
  10093. this.resetTextureCache();
  10094. this._currentEffect = null;
  10095. // 6/8/2017: deltakosh: Should not be required anymore.
  10096. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10097. if (bruteForce) {
  10098. this._currentProgram = null;
  10099. this._stencilState.reset();
  10100. this._depthCullingState.reset();
  10101. this.setDepthFunctionToLessOrEqual();
  10102. this._alphaState.reset();
  10103. }
  10104. this._cachedVertexBuffers = null;
  10105. this._cachedIndexBuffer = null;
  10106. this._cachedEffectForVertexBuffers = null;
  10107. this._unbindVertexArrayObject();
  10108. this.bindIndexBuffer(null);
  10109. this.bindArrayBuffer(null);
  10110. };
  10111. /**
  10112. * Set the compressed texture format to use, based on the formats you have, and the formats
  10113. * supported by the hardware / browser.
  10114. *
  10115. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10116. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10117. * to API arguments needed to compressed textures. This puts the burden on the container
  10118. * generator to house the arcane code for determining these for current & future formats.
  10119. *
  10120. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10121. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10122. *
  10123. * Note: The result of this call is not taken into account when a texture is base64.
  10124. *
  10125. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10126. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10127. *
  10128. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10129. * @returns The extension selected.
  10130. */
  10131. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10132. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10133. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10134. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10135. return this._textureFormatInUse = this._texturesSupported[i];
  10136. }
  10137. }
  10138. }
  10139. // actively set format to nothing, to allow this to be called more than once
  10140. // and possibly fail the 2nd time
  10141. this._textureFormatInUse = null;
  10142. return null;
  10143. };
  10144. Engine.prototype._createTexture = function () {
  10145. var texture = this._gl.createTexture();
  10146. if (!texture) {
  10147. throw new Error("Unable to create texture");
  10148. }
  10149. return texture;
  10150. };
  10151. /**
  10152. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10153. * @param {string} urlArg- This contains one of the following:
  10154. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10155. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10156. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10157. *
  10158. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10159. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10160. * @param {Scene} scene- Needed for loading to the correct scene.
  10161. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10162. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10163. * @param {callback} onError- Optional callback to be called upon failure.
  10164. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10165. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10166. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10167. *
  10168. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10169. */
  10170. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10171. var _this = this;
  10172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10173. if (onLoad === void 0) { onLoad = null; }
  10174. if (onError === void 0) { onError = null; }
  10175. if (buffer === void 0) { buffer = null; }
  10176. if (fallBack === void 0) { fallBack = null; }
  10177. if (format === void 0) { format = null; }
  10178. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10179. var fromData = url.substr(0, 5) === "data:";
  10180. var fromBlob = url.substr(0, 5) === "blob:";
  10181. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10182. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10183. // establish the file extension, if possible
  10184. var lastDot = url.lastIndexOf('.');
  10185. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10186. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10187. var isTGA = (extension === ".tga");
  10188. // determine if a ktx file should be substituted
  10189. var isKTX = false;
  10190. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10191. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10192. isKTX = true;
  10193. }
  10194. if (scene) {
  10195. scene._addPendingData(texture);
  10196. }
  10197. texture.url = url;
  10198. texture.generateMipMaps = !noMipmap;
  10199. texture.samplingMode = samplingMode;
  10200. texture.invertY = invertY;
  10201. if (!this._doNotHandleContextLost) {
  10202. // Keep a link to the buffer only if we plan to handle context lost
  10203. texture._buffer = buffer;
  10204. }
  10205. if (onLoad) {
  10206. texture.onLoadedObservable.add(onLoad);
  10207. }
  10208. if (!fallBack)
  10209. this._internalTexturesCache.push(texture);
  10210. var onerror = function () {
  10211. if (scene) {
  10212. scene._removePendingData(texture);
  10213. }
  10214. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10215. if (isKTX) {
  10216. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10217. }
  10218. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10219. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10220. }
  10221. else if (onError) {
  10222. onError();
  10223. }
  10224. };
  10225. var callback = null;
  10226. // processing for non-image formats
  10227. if (isKTX || isTGA || isDDS) {
  10228. if (isKTX) {
  10229. callback = function (data) {
  10230. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10231. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10232. ktx.uploadLevels(_this._gl, !noMipmap);
  10233. return false;
  10234. }, samplingMode);
  10235. };
  10236. }
  10237. else if (isTGA) {
  10238. callback = function (arrayBuffer) {
  10239. var data = new Uint8Array(arrayBuffer);
  10240. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10241. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10242. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10243. return false;
  10244. }, samplingMode);
  10245. };
  10246. }
  10247. else if (isDDS) {
  10248. callback = function (data) {
  10249. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10250. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10251. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10252. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10253. return false;
  10254. }, samplingMode);
  10255. };
  10256. }
  10257. if (!buffer) {
  10258. BABYLON.Tools.LoadFile(url, function (data) {
  10259. if (callback) {
  10260. callback(data);
  10261. }
  10262. }, undefined, scene ? scene.database : undefined, true, onerror);
  10263. }
  10264. else {
  10265. if (callback) {
  10266. callback(buffer);
  10267. }
  10268. }
  10269. // image format processing
  10270. }
  10271. else {
  10272. var onload = function (img) {
  10273. if (fromBlob && !_this._doNotHandleContextLost) {
  10274. // We need to store the image if we need to rebuild the texture
  10275. // in case of a webgl context lost
  10276. texture._buffer = img;
  10277. }
  10278. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10279. var gl = _this._gl;
  10280. var isPot = (img.width === potWidth && img.height === potHeight);
  10281. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10282. if (isPot) {
  10283. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10284. return false;
  10285. }
  10286. // Using shaders to rescale because canvas.drawImage is lossy
  10287. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10288. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10289. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10292. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10294. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10295. _this._releaseTexture(source);
  10296. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10297. continuationCallback();
  10298. });
  10299. return true;
  10300. }, samplingMode);
  10301. };
  10302. if (!fromData || isBase64)
  10303. if (buffer instanceof HTMLImageElement) {
  10304. onload(buffer);
  10305. }
  10306. else {
  10307. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10308. }
  10309. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10310. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10311. else
  10312. onload(buffer);
  10313. }
  10314. return texture;
  10315. };
  10316. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10317. var _this = this;
  10318. var rtt = this.createRenderTargetTexture({
  10319. width: destination.width,
  10320. height: destination.height,
  10321. }, {
  10322. generateMipMaps: false,
  10323. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10324. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10325. generateDepthBuffer: false,
  10326. generateStencilBuffer: false
  10327. });
  10328. if (!this._rescalePostProcess) {
  10329. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10330. }
  10331. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10332. _this._rescalePostProcess.onApply = function (effect) {
  10333. effect._bindTexture("textureSampler", source);
  10334. };
  10335. var hostingScene = scene;
  10336. if (!hostingScene) {
  10337. hostingScene = _this.scenes[_this.scenes.length - 1];
  10338. }
  10339. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10340. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10341. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10342. _this.unBindFramebuffer(rtt);
  10343. _this._releaseTexture(rtt);
  10344. if (onComplete) {
  10345. onComplete();
  10346. }
  10347. });
  10348. };
  10349. Engine.prototype._getInternalFormat = function (format) {
  10350. var internalFormat = this._gl.RGBA;
  10351. switch (format) {
  10352. case Engine.TEXTUREFORMAT_ALPHA:
  10353. internalFormat = this._gl.ALPHA;
  10354. break;
  10355. case Engine.TEXTUREFORMAT_LUMINANCE:
  10356. internalFormat = this._gl.LUMINANCE;
  10357. break;
  10358. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10359. internalFormat = this._gl.LUMINANCE_ALPHA;
  10360. break;
  10361. case Engine.TEXTUREFORMAT_RGB:
  10362. internalFormat = this._gl.RGB;
  10363. break;
  10364. case Engine.TEXTUREFORMAT_RGBA:
  10365. internalFormat = this._gl.RGBA;
  10366. break;
  10367. }
  10368. return internalFormat;
  10369. };
  10370. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10371. if (compression === void 0) { compression = null; }
  10372. if (!texture) {
  10373. return;
  10374. }
  10375. var internalFormat = this._getInternalFormat(format);
  10376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10378. if (!this._doNotHandleContextLost) {
  10379. texture._bufferView = data;
  10380. texture.format = format;
  10381. texture.invertY = invertY;
  10382. texture._compression = compression;
  10383. }
  10384. if (texture.width % 4 !== 0) {
  10385. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10386. }
  10387. if (compression && data) {
  10388. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10389. }
  10390. else {
  10391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10392. }
  10393. if (texture.generateMipMaps) {
  10394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10395. }
  10396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10397. this.resetTextureCache();
  10398. texture.isReady = true;
  10399. };
  10400. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10401. if (compression === void 0) { compression = null; }
  10402. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10403. texture.baseWidth = width;
  10404. texture.baseHeight = height;
  10405. texture.width = width;
  10406. texture.height = height;
  10407. texture.format = format;
  10408. texture.generateMipMaps = generateMipMaps;
  10409. texture.samplingMode = samplingMode;
  10410. texture.invertY = invertY;
  10411. texture._compression = compression;
  10412. if (!this._doNotHandleContextLost) {
  10413. texture._bufferView = data;
  10414. }
  10415. this.updateRawTexture(texture, data, format, invertY, compression);
  10416. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10417. // Filters
  10418. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10419. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10420. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10421. if (generateMipMaps) {
  10422. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10423. }
  10424. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10425. this._internalTexturesCache.push(texture);
  10426. return texture;
  10427. };
  10428. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10429. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10430. texture.baseWidth = width;
  10431. texture.baseHeight = height;
  10432. if (generateMipMaps) {
  10433. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10434. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10435. }
  10436. this.resetTextureCache();
  10437. texture.width = width;
  10438. texture.height = height;
  10439. texture.isReady = false;
  10440. texture.generateMipMaps = generateMipMaps;
  10441. texture.samplingMode = samplingMode;
  10442. this.updateTextureSamplingMode(samplingMode, texture);
  10443. this._internalTexturesCache.push(texture);
  10444. return texture;
  10445. };
  10446. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10447. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10448. if (texture.isCube) {
  10449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10450. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10451. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10452. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10453. }
  10454. else if (texture.is3D) {
  10455. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10456. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10457. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10458. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10459. }
  10460. else {
  10461. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10462. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10463. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10464. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10465. }
  10466. texture.samplingMode = samplingMode;
  10467. };
  10468. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10469. if (premulAlpha === void 0) { premulAlpha = false; }
  10470. if (!texture) {
  10471. return;
  10472. }
  10473. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10474. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10475. if (premulAlpha) {
  10476. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10477. }
  10478. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10479. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10480. if (texture.generateMipMaps) {
  10481. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10482. }
  10483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10484. if (premulAlpha) {
  10485. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10486. }
  10487. this.resetTextureCache();
  10488. texture.isReady = true;
  10489. };
  10490. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10491. if (!texture || texture._isDisabled) {
  10492. return;
  10493. }
  10494. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10495. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10496. try {
  10497. // Testing video texture support
  10498. if (this._videoTextureSupported === undefined) {
  10499. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10500. if (this._gl.getError() !== 0) {
  10501. this._videoTextureSupported = false;
  10502. }
  10503. else {
  10504. this._videoTextureSupported = true;
  10505. }
  10506. }
  10507. // Copy video through the current working canvas if video texture is not supported
  10508. if (!this._videoTextureSupported) {
  10509. if (!texture._workingCanvas) {
  10510. texture._workingCanvas = document.createElement("canvas");
  10511. var context = texture._workingCanvas.getContext("2d");
  10512. if (!context) {
  10513. throw new Error("Unable to get 2d context");
  10514. }
  10515. texture._workingContext = context;
  10516. texture._workingCanvas.width = texture.width;
  10517. texture._workingCanvas.height = texture.height;
  10518. }
  10519. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10520. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10521. }
  10522. else {
  10523. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10524. }
  10525. if (texture.generateMipMaps) {
  10526. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10527. }
  10528. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10529. this.resetTextureCache();
  10530. texture.isReady = true;
  10531. }
  10532. catch (ex) {
  10533. // Something unexpected
  10534. // Let's disable the texture
  10535. texture._isDisabled = true;
  10536. }
  10537. };
  10538. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10539. var fullOptions = new RenderTargetCreationOptions();
  10540. if (options !== undefined && typeof options === "object") {
  10541. fullOptions.generateMipMaps = options.generateMipMaps;
  10542. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10543. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10544. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10545. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10546. }
  10547. else {
  10548. fullOptions.generateMipMaps = options;
  10549. fullOptions.generateDepthBuffer = true;
  10550. fullOptions.generateStencilBuffer = false;
  10551. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10552. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10553. }
  10554. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10555. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10556. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10557. }
  10558. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10559. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10560. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10561. }
  10562. var gl = this._gl;
  10563. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10564. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10565. var width = size.width || size;
  10566. var height = size.height || size;
  10567. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10568. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10569. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10570. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10571. }
  10572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10576. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10577. // Create the framebuffer
  10578. var framebuffer = gl.createFramebuffer();
  10579. this.bindUnboundFramebuffer(framebuffer);
  10580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10581. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10582. if (fullOptions.generateMipMaps) {
  10583. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10584. }
  10585. // Unbind
  10586. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10587. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10588. this.bindUnboundFramebuffer(null);
  10589. texture._framebuffer = framebuffer;
  10590. texture.baseWidth = width;
  10591. texture.baseHeight = height;
  10592. texture.width = width;
  10593. texture.height = height;
  10594. texture.isReady = true;
  10595. texture.samples = 1;
  10596. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10597. texture.samplingMode = fullOptions.samplingMode;
  10598. texture.type = fullOptions.type;
  10599. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10600. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10601. this.resetTextureCache();
  10602. this._internalTexturesCache.push(texture);
  10603. return texture;
  10604. };
  10605. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10606. var generateMipMaps = false;
  10607. var generateDepthBuffer = true;
  10608. var generateStencilBuffer = false;
  10609. var generateDepthTexture = false;
  10610. var textureCount = 1;
  10611. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10612. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10613. var types = [], samplingModes = [];
  10614. if (options !== undefined) {
  10615. generateMipMaps = options.generateMipMaps;
  10616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10617. generateStencilBuffer = options.generateStencilBuffer;
  10618. generateDepthTexture = options.generateDepthTexture;
  10619. textureCount = options.textureCount || 1;
  10620. if (options.types) {
  10621. types = options.types;
  10622. }
  10623. if (options.samplingModes) {
  10624. samplingModes = options.samplingModes;
  10625. }
  10626. }
  10627. var gl = this._gl;
  10628. // Create the framebuffer
  10629. var framebuffer = gl.createFramebuffer();
  10630. this.bindUnboundFramebuffer(framebuffer);
  10631. var width = size.width || size;
  10632. var height = size.height || size;
  10633. var textures = [];
  10634. var attachments = [];
  10635. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10636. for (var i = 0; i < textureCount; i++) {
  10637. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10638. var type = types[i] || defaultType;
  10639. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10640. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10641. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10642. }
  10643. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10644. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10645. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10646. }
  10647. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10648. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10649. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10650. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10651. }
  10652. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10653. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10654. textures.push(texture);
  10655. attachments.push(attachment);
  10656. gl.activeTexture(gl["TEXTURE" + i]);
  10657. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10658. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10660. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10662. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10663. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10664. if (generateMipMaps) {
  10665. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10666. }
  10667. // Unbind
  10668. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10669. texture._framebuffer = framebuffer;
  10670. texture._depthStencilBuffer = depthStencilBuffer;
  10671. texture.baseWidth = width;
  10672. texture.baseHeight = height;
  10673. texture.width = width;
  10674. texture.height = height;
  10675. texture.isReady = true;
  10676. texture.samples = 1;
  10677. texture.generateMipMaps = generateMipMaps;
  10678. texture.samplingMode = samplingMode;
  10679. texture.type = type;
  10680. texture._generateDepthBuffer = generateDepthBuffer;
  10681. texture._generateStencilBuffer = generateStencilBuffer;
  10682. this._internalTexturesCache.push(texture);
  10683. }
  10684. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10685. // Depth texture
  10686. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10687. gl.activeTexture(gl.TEXTURE0);
  10688. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10693. 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);
  10694. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10695. depthTexture._framebuffer = framebuffer;
  10696. depthTexture.baseWidth = width;
  10697. depthTexture.baseHeight = height;
  10698. depthTexture.width = width;
  10699. depthTexture.height = height;
  10700. depthTexture.isReady = true;
  10701. depthTexture.samples = 1;
  10702. depthTexture.generateMipMaps = generateMipMaps;
  10703. depthTexture.samplingMode = gl.NEAREST;
  10704. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10705. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10706. textures.push(depthTexture);
  10707. this._internalTexturesCache.push(depthTexture);
  10708. }
  10709. gl.drawBuffers(attachments);
  10710. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10711. this.bindUnboundFramebuffer(null);
  10712. this.resetTextureCache();
  10713. return textures;
  10714. };
  10715. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10716. if (samples === void 0) { samples = 1; }
  10717. var depthStencilBuffer = null;
  10718. var gl = this._gl;
  10719. // Create the depth/stencil buffer
  10720. if (generateStencilBuffer) {
  10721. depthStencilBuffer = gl.createRenderbuffer();
  10722. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10723. if (samples > 1) {
  10724. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10725. }
  10726. else {
  10727. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10728. }
  10729. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10730. }
  10731. else if (generateDepthBuffer) {
  10732. depthStencilBuffer = gl.createRenderbuffer();
  10733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10734. if (samples > 1) {
  10735. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10736. }
  10737. else {
  10738. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10739. }
  10740. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10741. }
  10742. return depthStencilBuffer;
  10743. };
  10744. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10745. if (this.webGLVersion < 2 || !texture) {
  10746. return 1;
  10747. }
  10748. if (texture.samples === samples) {
  10749. return samples;
  10750. }
  10751. var gl = this._gl;
  10752. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10753. // Dispose previous render buffers
  10754. if (texture._depthStencilBuffer) {
  10755. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10756. }
  10757. if (texture._MSAAFramebuffer) {
  10758. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10759. }
  10760. if (texture._MSAARenderBuffer) {
  10761. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10762. }
  10763. if (samples > 1) {
  10764. var framebuffer = gl.createFramebuffer();
  10765. if (!framebuffer) {
  10766. throw new Error("Unable to create multi sampled framebuffer");
  10767. }
  10768. texture._MSAAFramebuffer = framebuffer;
  10769. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10770. var colorRenderbuffer = gl.createRenderbuffer();
  10771. if (!colorRenderbuffer) {
  10772. throw new Error("Unable to create multi sampled framebuffer");
  10773. }
  10774. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10775. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10776. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10777. texture._MSAARenderBuffer = colorRenderbuffer;
  10778. }
  10779. else {
  10780. this.bindUnboundFramebuffer(texture._framebuffer);
  10781. }
  10782. texture.samples = samples;
  10783. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10784. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10785. this.bindUnboundFramebuffer(null);
  10786. return samples;
  10787. };
  10788. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10789. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10790. };
  10791. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10792. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10793. };
  10794. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10795. var gl = this._gl;
  10796. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10797. var generateMipMaps = true;
  10798. var generateDepthBuffer = true;
  10799. var generateStencilBuffer = false;
  10800. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10801. if (options !== undefined) {
  10802. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10803. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10804. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10805. if (options.samplingMode !== undefined) {
  10806. samplingMode = options.samplingMode;
  10807. }
  10808. }
  10809. texture.isCube = true;
  10810. texture.generateMipMaps = generateMipMaps;
  10811. texture.samples = 1;
  10812. texture.samplingMode = samplingMode;
  10813. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10815. for (var face = 0; face < 6; face++) {
  10816. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10817. }
  10818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10822. // Create the framebuffer
  10823. var framebuffer = gl.createFramebuffer();
  10824. this.bindUnboundFramebuffer(framebuffer);
  10825. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10826. // Mipmaps
  10827. if (texture.generateMipMaps) {
  10828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10829. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10830. }
  10831. // Unbind
  10832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10833. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10834. this.bindUnboundFramebuffer(null);
  10835. texture._framebuffer = framebuffer;
  10836. texture.width = size;
  10837. texture.height = size;
  10838. texture.isReady = true;
  10839. this.resetTextureCache();
  10840. this._internalTexturesCache.push(texture);
  10841. return texture;
  10842. };
  10843. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10844. var _this = this;
  10845. if (onLoad === void 0) { onLoad = null; }
  10846. if (onError === void 0) { onError = null; }
  10847. if (forcedExtension === void 0) { forcedExtension = null; }
  10848. var callback = function (loadData) {
  10849. if (!loadData) {
  10850. if (onLoad) {
  10851. onLoad(null);
  10852. }
  10853. return;
  10854. }
  10855. var texture = loadData.texture;
  10856. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10857. texture._lodGenerationScale = scale;
  10858. texture._lodGenerationOffset = offset;
  10859. if (_this._caps.textureLOD) {
  10860. // Do not add extra process if texture lod is supported.
  10861. if (onLoad) {
  10862. onLoad(texture);
  10863. }
  10864. return;
  10865. }
  10866. var mipSlices = 3;
  10867. var gl = _this._gl;
  10868. var width = loadData.width;
  10869. if (!width) {
  10870. return;
  10871. }
  10872. var textures = [];
  10873. for (var i = 0; i < mipSlices; i++) {
  10874. //compute LOD from even spacing in smoothness (matching shader calculation)
  10875. var smoothness = i / (mipSlices - 1);
  10876. var roughness = 1 - smoothness;
  10877. var minLODIndex = offset; // roughness = 0
  10878. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10879. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10880. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10881. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10882. glTextureFromLod.isCube = true;
  10883. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10888. if (loadData.isDDS) {
  10889. var info = loadData.info;
  10890. var data = loadData.data;
  10891. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10892. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10893. }
  10894. else {
  10895. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10896. }
  10897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10898. // Wrap in a base texture for easy binding.
  10899. var lodTexture = new BABYLON.BaseTexture(scene);
  10900. lodTexture.isCube = true;
  10901. lodTexture._texture = glTextureFromLod;
  10902. glTextureFromLod.isReady = true;
  10903. textures.push(lodTexture);
  10904. }
  10905. texture._lodTextureHigh = textures[2];
  10906. texture._lodTextureMid = textures[1];
  10907. texture._lodTextureLow = textures[0];
  10908. if (onLoad) {
  10909. onLoad(texture);
  10910. }
  10911. };
  10912. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10913. };
  10914. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10915. var _this = this;
  10916. if (onLoad === void 0) { onLoad = null; }
  10917. if (onError === void 0) { onError = null; }
  10918. if (forcedExtension === void 0) { forcedExtension = null; }
  10919. var gl = this._gl;
  10920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10921. texture.isCube = true;
  10922. texture.url = rootUrl;
  10923. texture.generateMipMaps = !noMipmap;
  10924. if (!this._doNotHandleContextLost) {
  10925. texture._extension = forcedExtension;
  10926. texture._files = files;
  10927. }
  10928. var isKTX = false;
  10929. var isDDS = false;
  10930. var lastDot = rootUrl.lastIndexOf('.');
  10931. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10932. if (this._textureFormatInUse) {
  10933. extension = this._textureFormatInUse;
  10934. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10935. isKTX = true;
  10936. }
  10937. else {
  10938. isDDS = (extension === ".dds");
  10939. }
  10940. var onerror = function (request, exception) {
  10941. if (onError) {
  10942. onError(request.status + " " + request.statusText, exception);
  10943. }
  10944. };
  10945. if (isKTX) {
  10946. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10947. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10948. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10949. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10950. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10951. ktx.uploadLevels(_this._gl, !noMipmap);
  10952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10956. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10957. _this.resetTextureCache();
  10958. texture.width = ktx.pixelWidth;
  10959. texture.height = ktx.pixelHeight;
  10960. texture.isReady = true;
  10961. }, undefined, undefined, true, onerror);
  10962. }
  10963. else if (isDDS) {
  10964. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10965. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10966. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10967. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10969. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10970. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10971. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10972. }
  10973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10975. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10977. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10978. _this.resetTextureCache();
  10979. texture.width = info.width;
  10980. texture.height = info.height;
  10981. texture.isReady = true;
  10982. texture.type = info.textureType;
  10983. if (onLoad) {
  10984. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10985. }
  10986. }, undefined, undefined, true, onerror);
  10987. }
  10988. else {
  10989. if (!files) {
  10990. throw new Error("Cannot load cubemap because files were not defined");
  10991. }
  10992. cascadeLoad(rootUrl, scene, function (imgs) {
  10993. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10994. var height = width;
  10995. _this._prepareWorkingCanvas();
  10996. if (!_this._workingCanvas || !_this._workingContext) {
  10997. return;
  10998. }
  10999. _this._workingCanvas.width = width;
  11000. _this._workingCanvas.height = height;
  11001. var faces = [
  11002. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11003. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11004. ];
  11005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11006. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11007. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11008. for (var index = 0; index < faces.length; index++) {
  11009. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11010. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11011. }
  11012. if (!noMipmap) {
  11013. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11014. }
  11015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11018. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11019. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11020. _this.resetTextureCache();
  11021. texture.width = width;
  11022. texture.height = height;
  11023. texture.isReady = true;
  11024. if (format) {
  11025. texture.format = format;
  11026. }
  11027. texture.onLoadedObservable.notifyObservers(texture);
  11028. texture.onLoadedObservable.clear();
  11029. if (onLoad) {
  11030. onLoad();
  11031. }
  11032. }, files, onError);
  11033. }
  11034. this._internalTexturesCache.push(texture);
  11035. return texture;
  11036. };
  11037. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11038. if (compression === void 0) { compression = null; }
  11039. if (level === void 0) { level = 0; }
  11040. texture._bufferViewArray = data;
  11041. texture.format = format;
  11042. texture.type = type;
  11043. texture.invertY = invertY;
  11044. texture._compression = compression;
  11045. var gl = this._gl;
  11046. var textureType = this._getWebGLTextureType(type);
  11047. var internalFormat = this._getInternalFormat(format);
  11048. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11049. var needConversion = false;
  11050. if (internalFormat === gl.RGB) {
  11051. internalFormat = gl.RGBA;
  11052. needConversion = true;
  11053. }
  11054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11055. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11056. if (texture.width % 4 !== 0) {
  11057. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11058. }
  11059. // Data are known to be in +X +Y +Z -X -Y -Z
  11060. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11061. var faceData = data[faceIndex];
  11062. if (compression) {
  11063. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11064. }
  11065. else {
  11066. if (needConversion) {
  11067. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11068. }
  11069. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11070. }
  11071. }
  11072. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11073. if (isPot && texture.generateMipMaps && level === 0) {
  11074. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11075. }
  11076. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11077. this.resetTextureCache();
  11078. texture.isReady = true;
  11079. };
  11080. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11081. if (compression === void 0) { compression = null; }
  11082. var gl = this._gl;
  11083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11084. texture.isCube = true;
  11085. texture.generateMipMaps = generateMipMaps;
  11086. texture.format = format;
  11087. texture.type = type;
  11088. if (!this._doNotHandleContextLost) {
  11089. texture._bufferViewArray = data;
  11090. }
  11091. var textureType = this._getWebGLTextureType(type);
  11092. var internalFormat = this._getInternalFormat(format);
  11093. var needConversion = false;
  11094. if (internalFormat === gl.RGB) {
  11095. internalFormat = gl.RGBA;
  11096. needConversion = true;
  11097. }
  11098. var width = size;
  11099. var height = width;
  11100. texture.width = width;
  11101. texture.height = height;
  11102. // Double check on POT to generate Mips.
  11103. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11104. if (!isPot) {
  11105. generateMipMaps = false;
  11106. }
  11107. // Upload data if needed. The texture won't be ready until then.
  11108. if (data) {
  11109. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11110. }
  11111. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11112. // Filters
  11113. if (data && generateMipMaps) {
  11114. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11115. }
  11116. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11119. }
  11120. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11123. }
  11124. else {
  11125. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11128. }
  11129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11131. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11132. return texture;
  11133. };
  11134. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11135. var _this = this;
  11136. if (onLoad === void 0) { onLoad = null; }
  11137. if (onError === void 0) { onError = null; }
  11138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11139. if (invertY === void 0) { invertY = false; }
  11140. var gl = this._gl;
  11141. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11142. scene._addPendingData(texture);
  11143. texture.url = url;
  11144. this._internalTexturesCache.push(texture);
  11145. var onerror = function (request, exception) {
  11146. scene._removePendingData(texture);
  11147. if (onError) {
  11148. onError(request.status + " " + request.statusText, exception);
  11149. }
  11150. };
  11151. var internalCallback = function (data) {
  11152. var width = texture.width;
  11153. var faceDataArrays = callback(data);
  11154. if (!faceDataArrays) {
  11155. return;
  11156. }
  11157. if (mipmmapGenerator) {
  11158. var textureType = _this._getWebGLTextureType(type);
  11159. var internalFormat = _this._getInternalFormat(format);
  11160. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11161. var needConversion = false;
  11162. if (internalFormat === gl.RGB) {
  11163. internalFormat = gl.RGBA;
  11164. needConversion = true;
  11165. }
  11166. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11167. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11168. var mipData = mipmmapGenerator(faceDataArrays);
  11169. for (var level = 0; level < mipData.length; level++) {
  11170. var mipSize = width >> level;
  11171. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11172. var mipFaceData = mipData[level][faceIndex];
  11173. if (needConversion) {
  11174. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11175. }
  11176. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11177. }
  11178. }
  11179. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11180. }
  11181. else {
  11182. texture.generateMipMaps = !noMipmap;
  11183. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11184. }
  11185. texture.isReady = true;
  11186. _this.resetTextureCache();
  11187. scene._removePendingData(texture);
  11188. if (onLoad) {
  11189. onLoad();
  11190. }
  11191. };
  11192. BABYLON.Tools.LoadFile(url, function (data) {
  11193. internalCallback(data);
  11194. }, undefined, scene.database, true, onerror);
  11195. return texture;
  11196. };
  11197. ;
  11198. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11199. if (compression === void 0) { compression = null; }
  11200. var internalFormat = this._getInternalFormat(format);
  11201. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11202. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11203. if (!this._doNotHandleContextLost) {
  11204. texture._bufferView = data;
  11205. texture.format = format;
  11206. texture.invertY = invertY;
  11207. texture._compression = compression;
  11208. }
  11209. if (texture.width % 4 !== 0) {
  11210. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11211. }
  11212. if (compression && data) {
  11213. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11214. }
  11215. else {
  11216. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11217. }
  11218. if (texture.generateMipMaps) {
  11219. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11220. }
  11221. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11222. this.resetTextureCache();
  11223. texture.isReady = true;
  11224. };
  11225. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11226. if (compression === void 0) { compression = null; }
  11227. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11228. texture.baseWidth = width;
  11229. texture.baseHeight = height;
  11230. texture.baseDepth = depth;
  11231. texture.width = width;
  11232. texture.height = height;
  11233. texture.depth = depth;
  11234. texture.format = format;
  11235. texture.generateMipMaps = generateMipMaps;
  11236. texture.samplingMode = samplingMode;
  11237. texture.is3D = true;
  11238. if (!this._doNotHandleContextLost) {
  11239. texture._bufferView = data;
  11240. }
  11241. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11242. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11243. // Filters
  11244. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11245. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11246. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11247. if (generateMipMaps) {
  11248. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11249. }
  11250. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11251. this._internalTexturesCache.push(texture);
  11252. return texture;
  11253. };
  11254. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11255. var gl = this._gl;
  11256. if (!gl) {
  11257. return;
  11258. }
  11259. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11262. if (!noMipmap && !isCompressed) {
  11263. gl.generateMipmap(gl.TEXTURE_2D);
  11264. }
  11265. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11266. this.resetTextureCache();
  11267. if (scene) {
  11268. scene._removePendingData(texture);
  11269. }
  11270. texture.onLoadedObservable.notifyObservers(texture);
  11271. texture.onLoadedObservable.clear();
  11272. };
  11273. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11274. var _this = this;
  11275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11276. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11277. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11278. var gl = this._gl;
  11279. if (!gl) {
  11280. return;
  11281. }
  11282. if (!texture._webGLTexture) {
  11283. this.resetTextureCache();
  11284. if (scene) {
  11285. scene._removePendingData(texture);
  11286. }
  11287. return;
  11288. }
  11289. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11290. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11291. texture.baseWidth = width;
  11292. texture.baseHeight = height;
  11293. texture.width = potWidth;
  11294. texture.height = potHeight;
  11295. texture.isReady = true;
  11296. if (processFunction(potWidth, potHeight, function () {
  11297. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11298. })) {
  11299. // Returning as texture needs extra async steps
  11300. return;
  11301. }
  11302. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11303. };
  11304. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11305. // Create new RGBA data container.
  11306. var rgbaData;
  11307. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11308. rgbaData = new Float32Array(width * height * 4);
  11309. }
  11310. else {
  11311. rgbaData = new Uint32Array(width * height * 4);
  11312. }
  11313. // Convert each pixel.
  11314. for (var x = 0; x < width; x++) {
  11315. for (var y = 0; y < height; y++) {
  11316. var index = (y * width + x) * 3;
  11317. var newIndex = (y * width + x) * 4;
  11318. // Map Old Value to new value.
  11319. rgbaData[newIndex + 0] = rgbData[index + 0];
  11320. rgbaData[newIndex + 1] = rgbData[index + 1];
  11321. rgbaData[newIndex + 2] = rgbData[index + 2];
  11322. // Add fully opaque alpha channel.
  11323. rgbaData[newIndex + 3] = 1;
  11324. }
  11325. }
  11326. return rgbaData;
  11327. };
  11328. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11329. var gl = this._gl;
  11330. if (texture._framebuffer) {
  11331. gl.deleteFramebuffer(texture._framebuffer);
  11332. texture._framebuffer = null;
  11333. }
  11334. if (texture._depthStencilBuffer) {
  11335. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11336. texture._depthStencilBuffer = null;
  11337. }
  11338. if (texture._MSAAFramebuffer) {
  11339. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11340. texture._MSAAFramebuffer = null;
  11341. }
  11342. if (texture._MSAARenderBuffer) {
  11343. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11344. texture._MSAARenderBuffer = null;
  11345. }
  11346. };
  11347. Engine.prototype._releaseTexture = function (texture) {
  11348. var gl = this._gl;
  11349. this._releaseFramebufferObjects(texture);
  11350. gl.deleteTexture(texture._webGLTexture);
  11351. // Unbind channels
  11352. this.unbindAllTextures();
  11353. var index = this._internalTexturesCache.indexOf(texture);
  11354. if (index !== -1) {
  11355. this._internalTexturesCache.splice(index, 1);
  11356. }
  11357. // Integrated fixed lod samplers.
  11358. if (texture._lodTextureHigh) {
  11359. texture._lodTextureHigh.dispose();
  11360. }
  11361. if (texture._lodTextureMid) {
  11362. texture._lodTextureMid.dispose();
  11363. }
  11364. if (texture._lodTextureLow) {
  11365. texture._lodTextureLow.dispose();
  11366. }
  11367. };
  11368. Engine.prototype.setProgram = function (program) {
  11369. if (this._currentProgram !== program) {
  11370. this._gl.useProgram(program);
  11371. this._currentProgram = program;
  11372. }
  11373. };
  11374. Engine.prototype.bindSamplers = function (effect) {
  11375. this.setProgram(effect.getProgram());
  11376. var samplers = effect.getSamplers();
  11377. for (var index = 0; index < samplers.length; index++) {
  11378. var uniform = effect.getUniform(samplers[index]);
  11379. this._gl.uniform1i(uniform, index);
  11380. }
  11381. this._currentEffect = null;
  11382. };
  11383. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11384. if (this._activeTextureChannel !== textureChannel) {
  11385. this._gl.activeTexture(textureChannel);
  11386. this._activeTextureChannel = textureChannel;
  11387. }
  11388. };
  11389. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11390. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11391. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11392. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11393. }
  11394. };
  11395. Engine.prototype._bindTexture = function (channel, texture) {
  11396. if (channel < 0) {
  11397. return;
  11398. }
  11399. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11400. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11401. };
  11402. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11403. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11404. };
  11405. Engine.prototype.unbindAllTextures = function () {
  11406. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11407. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11410. if (this.webGLVersion > 1) {
  11411. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11412. }
  11413. }
  11414. };
  11415. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11416. if (channel < 0) {
  11417. return;
  11418. }
  11419. if (this._setTexture(channel, texture)) {
  11420. this._gl.uniform1i(uniform, channel);
  11421. }
  11422. };
  11423. Engine.prototype._setTexture = function (channel, texture) {
  11424. // Not ready?
  11425. if (!texture) {
  11426. if (this._activeTexturesCache[channel] != null) {
  11427. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11428. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11430. if (this.webGLVersion > 1) {
  11431. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11432. }
  11433. }
  11434. return false;
  11435. }
  11436. // Video
  11437. var alreadyActivated = false;
  11438. if (texture.video) {
  11439. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11440. alreadyActivated = true;
  11441. texture.update();
  11442. }
  11443. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11444. texture.delayLoad();
  11445. return false;
  11446. }
  11447. var internalTexture;
  11448. if (texture.isReady()) {
  11449. internalTexture = texture.getInternalTexture();
  11450. }
  11451. else if (texture.isCube) {
  11452. internalTexture = this.emptyCubeTexture;
  11453. }
  11454. else if (texture.is3D) {
  11455. internalTexture = this.emptyTexture3D;
  11456. }
  11457. else {
  11458. internalTexture = this.emptyTexture;
  11459. }
  11460. if (!alreadyActivated) {
  11461. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11462. }
  11463. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11464. return false;
  11465. }
  11466. if (internalTexture && internalTexture.is3D) {
  11467. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11468. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11469. internalTexture._cachedWrapU = texture.wrapU;
  11470. switch (texture.wrapU) {
  11471. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11472. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11473. break;
  11474. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11475. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11476. break;
  11477. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11478. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11479. break;
  11480. }
  11481. }
  11482. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11483. internalTexture._cachedWrapV = texture.wrapV;
  11484. switch (texture.wrapV) {
  11485. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11486. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11487. break;
  11488. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11489. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11490. break;
  11491. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11492. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11493. break;
  11494. }
  11495. }
  11496. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11497. internalTexture._cachedWrapR = texture.wrapR;
  11498. switch (texture.wrapV) {
  11499. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11500. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11501. break;
  11502. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11503. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11504. break;
  11505. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11506. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11507. break;
  11508. }
  11509. }
  11510. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11511. }
  11512. else if (internalTexture && internalTexture.isCube) {
  11513. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11514. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11515. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11516. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11517. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11518. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11519. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11520. }
  11521. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11522. }
  11523. else {
  11524. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11525. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11526. internalTexture._cachedWrapU = texture.wrapU;
  11527. switch (texture.wrapU) {
  11528. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11530. break;
  11531. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11533. break;
  11534. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11536. break;
  11537. }
  11538. }
  11539. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11540. internalTexture._cachedWrapV = texture.wrapV;
  11541. switch (texture.wrapV) {
  11542. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11543. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11544. break;
  11545. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11546. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11547. break;
  11548. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11550. break;
  11551. }
  11552. }
  11553. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11554. }
  11555. return true;
  11556. };
  11557. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11558. if (channel < 0 || !uniform) {
  11559. return;
  11560. }
  11561. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11562. this._textureUnits = new Int32Array(textures.length);
  11563. }
  11564. for (var i = 0; i < textures.length; i++) {
  11565. this._textureUnits[i] = channel + i;
  11566. }
  11567. this._gl.uniform1iv(uniform, this._textureUnits);
  11568. for (var index = 0; index < textures.length; index++) {
  11569. this._setTexture(channel + index, textures[index]);
  11570. }
  11571. };
  11572. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11573. var internalTexture = texture.getInternalTexture();
  11574. if (!internalTexture) {
  11575. return;
  11576. }
  11577. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11578. var value = texture.anisotropicFilteringLevel;
  11579. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11580. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11581. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11582. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11583. }
  11584. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11585. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11586. internalTexture._cachedAnisotropicFilteringLevel = value;
  11587. }
  11588. };
  11589. Engine.prototype.readPixels = function (x, y, width, height) {
  11590. var data = new Uint8Array(height * width * 4);
  11591. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11592. return data;
  11593. };
  11594. /**
  11595. * Add an externaly attached data from its key.
  11596. * This method call will fail and return false, if such key already exists.
  11597. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11598. * @param key the unique key that identifies the data
  11599. * @param data the data object to associate to the key for this Engine instance
  11600. * @return true if no such key were already present and the data was added successfully, false otherwise
  11601. */
  11602. Engine.prototype.addExternalData = function (key, data) {
  11603. if (!this._externalData) {
  11604. this._externalData = new BABYLON.StringDictionary();
  11605. }
  11606. return this._externalData.add(key, data);
  11607. };
  11608. /**
  11609. * Get an externaly attached data from its key
  11610. * @param key the unique key that identifies the data
  11611. * @return the associated data, if present (can be null), or undefined if not present
  11612. */
  11613. Engine.prototype.getExternalData = function (key) {
  11614. if (!this._externalData) {
  11615. this._externalData = new BABYLON.StringDictionary();
  11616. }
  11617. return this._externalData.get(key);
  11618. };
  11619. /**
  11620. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11621. * @param key the unique key that identifies the data
  11622. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11623. * @return the associated data, can be null if the factory returned null.
  11624. */
  11625. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11626. if (!this._externalData) {
  11627. this._externalData = new BABYLON.StringDictionary();
  11628. }
  11629. return this._externalData.getOrAddWithFactory(key, factory);
  11630. };
  11631. /**
  11632. * Remove an externaly attached data from the Engine instance
  11633. * @param key the unique key that identifies the data
  11634. * @return true if the data was successfully removed, false if it doesn't exist
  11635. */
  11636. Engine.prototype.removeExternalData = function (key) {
  11637. if (!this._externalData) {
  11638. this._externalData = new BABYLON.StringDictionary();
  11639. }
  11640. return this._externalData.remove(key);
  11641. };
  11642. Engine.prototype.unbindAllAttributes = function () {
  11643. if (this._mustWipeVertexAttributes) {
  11644. this._mustWipeVertexAttributes = false;
  11645. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11646. this._gl.disableVertexAttribArray(i);
  11647. this._vertexAttribArraysEnabled[i] = false;
  11648. this._currentBufferPointers[i].active = false;
  11649. }
  11650. return;
  11651. }
  11652. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11653. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11654. continue;
  11655. }
  11656. this._gl.disableVertexAttribArray(i);
  11657. this._vertexAttribArraysEnabled[i] = false;
  11658. this._currentBufferPointers[i].active = false;
  11659. }
  11660. };
  11661. Engine.prototype.releaseEffects = function () {
  11662. for (var name in this._compiledEffects) {
  11663. this._deleteProgram(this._compiledEffects[name]._program);
  11664. }
  11665. this._compiledEffects = {};
  11666. };
  11667. // Dispose
  11668. Engine.prototype.dispose = function () {
  11669. this.hideLoadingUI();
  11670. this.stopRenderLoop();
  11671. // Release postProcesses
  11672. while (this.postProcesses.length) {
  11673. this.postProcesses[0].dispose();
  11674. }
  11675. // Empty texture
  11676. if (this._emptyTexture) {
  11677. this._releaseTexture(this._emptyTexture);
  11678. this._emptyTexture = null;
  11679. }
  11680. if (this._emptyCubeTexture) {
  11681. this._releaseTexture(this._emptyCubeTexture);
  11682. this._emptyCubeTexture = null;
  11683. }
  11684. // Rescale PP
  11685. if (this._rescalePostProcess) {
  11686. this._rescalePostProcess.dispose();
  11687. }
  11688. // Release scenes
  11689. while (this.scenes.length) {
  11690. this.scenes[0].dispose();
  11691. }
  11692. // Release audio engine
  11693. if (Engine.audioEngine) {
  11694. Engine.audioEngine.dispose();
  11695. }
  11696. // Release effects
  11697. this.releaseEffects();
  11698. // Unbind
  11699. this.unbindAllAttributes();
  11700. if (this._dummyFramebuffer) {
  11701. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11702. }
  11703. //WebVR
  11704. this.disableVR();
  11705. // Events
  11706. window.removeEventListener("blur", this._onBlur);
  11707. window.removeEventListener("focus", this._onFocus);
  11708. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11709. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11710. if (this._renderingCanvas) {
  11711. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11712. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11713. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11714. if (!this._doNotHandleContextLost) {
  11715. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11716. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11717. }
  11718. }
  11719. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11720. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11721. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11722. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11723. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11724. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11725. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11726. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11727. if (this._onVrDisplayConnect) {
  11728. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11729. if (this._onVrDisplayDisconnect) {
  11730. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11731. }
  11732. if (this._onVrDisplayPresentChange) {
  11733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11734. }
  11735. this._onVrDisplayConnect = null;
  11736. this._onVrDisplayDisconnect = null;
  11737. }
  11738. // Remove from Instances
  11739. var index = Engine.Instances.indexOf(this);
  11740. if (index >= 0) {
  11741. Engine.Instances.splice(index, 1);
  11742. }
  11743. this._workingCanvas = null;
  11744. this._workingContext = null;
  11745. this._currentBufferPointers = [];
  11746. this._renderingCanvas = null;
  11747. this._currentProgram = null;
  11748. this.onResizeObservable.clear();
  11749. this.onCanvasBlurObservable.clear();
  11750. this.onCanvasFocusObservable.clear();
  11751. this.onCanvasPointerOutObservable.clear();
  11752. this.onBeginFrameObservable.clear();
  11753. this.onEndFrameObservable.clear();
  11754. BABYLON.Effect.ResetCache();
  11755. };
  11756. // Loading screen
  11757. Engine.prototype.displayLoadingUI = function () {
  11758. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11759. return;
  11760. }
  11761. var loadingScreen = this.loadingScreen;
  11762. if (loadingScreen) {
  11763. loadingScreen.displayLoadingUI();
  11764. }
  11765. };
  11766. Engine.prototype.hideLoadingUI = function () {
  11767. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11768. return;
  11769. }
  11770. var loadingScreen = this.loadingScreen;
  11771. if (loadingScreen) {
  11772. loadingScreen.hideLoadingUI();
  11773. }
  11774. };
  11775. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11776. get: function () {
  11777. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11778. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11779. return this._loadingScreen;
  11780. },
  11781. set: function (loadingScreen) {
  11782. this._loadingScreen = loadingScreen;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11788. set: function (text) {
  11789. this.loadingScreen.loadingUIText = text;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11795. set: function (color) {
  11796. this.loadingScreen.loadingUIBackgroundColor = color;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Engine.prototype.attachContextLostEvent = function (callback) {
  11802. if (this._renderingCanvas) {
  11803. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11804. }
  11805. };
  11806. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11807. if (this._renderingCanvas) {
  11808. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11809. }
  11810. };
  11811. Engine.prototype.getVertexShaderSource = function (program) {
  11812. var shaders = this._gl.getAttachedShaders(program);
  11813. if (!shaders) {
  11814. return null;
  11815. }
  11816. return this._gl.getShaderSource(shaders[0]);
  11817. };
  11818. Engine.prototype.getFragmentShaderSource = function (program) {
  11819. var shaders = this._gl.getAttachedShaders(program);
  11820. if (!shaders) {
  11821. return null;
  11822. }
  11823. return this._gl.getShaderSource(shaders[1]);
  11824. };
  11825. Engine.prototype.getError = function () {
  11826. return this._gl.getError();
  11827. };
  11828. // FPS
  11829. Engine.prototype.getFps = function () {
  11830. return this._fps;
  11831. };
  11832. Engine.prototype.getDeltaTime = function () {
  11833. return this._deltaTime;
  11834. };
  11835. Engine.prototype._measureFps = function () {
  11836. this._performanceMonitor.sampleFrame();
  11837. this._fps = this._performanceMonitor.averageFPS;
  11838. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11839. };
  11840. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11841. if (faceIndex === void 0) { faceIndex = -1; }
  11842. var gl = this._gl;
  11843. if (!this._dummyFramebuffer) {
  11844. var dummy = gl.createFramebuffer();
  11845. if (!dummy) {
  11846. throw new Error("Unable to create dummy framebuffer");
  11847. }
  11848. this._dummyFramebuffer = dummy;
  11849. }
  11850. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11851. if (faceIndex > -1) {
  11852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11853. }
  11854. else {
  11855. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11856. }
  11857. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11858. var buffer;
  11859. switch (readType) {
  11860. case gl.UNSIGNED_BYTE:
  11861. buffer = new Uint8Array(4 * width * height);
  11862. readType = gl.UNSIGNED_BYTE;
  11863. break;
  11864. default:
  11865. buffer = new Float32Array(4 * width * height);
  11866. readType = gl.FLOAT;
  11867. break;
  11868. }
  11869. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11870. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11871. return buffer;
  11872. };
  11873. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11874. if (this._webGLVersion > 1) {
  11875. return this._caps.colorBufferFloat;
  11876. }
  11877. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11878. };
  11879. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11880. if (this._webGLVersion > 1) {
  11881. return this._caps.colorBufferFloat;
  11882. }
  11883. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11884. };
  11885. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11886. Engine.prototype._canRenderToFramebuffer = function (type) {
  11887. var gl = this._gl;
  11888. //clear existing errors
  11889. while (gl.getError() !== gl.NO_ERROR) { }
  11890. var successful = true;
  11891. var texture = gl.createTexture();
  11892. gl.bindTexture(gl.TEXTURE_2D, texture);
  11893. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11896. var fb = gl.createFramebuffer();
  11897. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11899. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11900. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11901. successful = successful && (gl.getError() === gl.NO_ERROR);
  11902. //try render by clearing frame buffer's color buffer
  11903. if (successful) {
  11904. gl.clear(gl.COLOR_BUFFER_BIT);
  11905. successful = successful && (gl.getError() === gl.NO_ERROR);
  11906. }
  11907. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11908. if (successful) {
  11909. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11910. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11911. var readFormat = gl.RGBA;
  11912. var readType = gl.UNSIGNED_BYTE;
  11913. var buffer = new Uint8Array(4);
  11914. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11915. successful = successful && (gl.getError() === gl.NO_ERROR);
  11916. }
  11917. //clean up
  11918. gl.deleteTexture(texture);
  11919. gl.deleteFramebuffer(fb);
  11920. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11921. //clear accumulated errors
  11922. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11923. return successful;
  11924. };
  11925. Engine.prototype._getWebGLTextureType = function (type) {
  11926. if (type === Engine.TEXTURETYPE_FLOAT) {
  11927. return this._gl.FLOAT;
  11928. }
  11929. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11930. // Add Half Float Constant.
  11931. return this._gl.HALF_FLOAT_OES;
  11932. }
  11933. return this._gl.UNSIGNED_BYTE;
  11934. };
  11935. ;
  11936. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11937. if (this._webGLVersion === 1) {
  11938. return this._gl.RGBA;
  11939. }
  11940. if (type === Engine.TEXTURETYPE_FLOAT) {
  11941. return this._gl.RGBA32F;
  11942. }
  11943. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11944. return this._gl.RGBA16F;
  11945. }
  11946. return this._gl.RGBA;
  11947. };
  11948. ;
  11949. Engine.prototype.createQuery = function () {
  11950. return this._gl.createQuery();
  11951. };
  11952. Engine.prototype.deleteQuery = function (query) {
  11953. this._gl.deleteQuery(query);
  11954. return this;
  11955. };
  11956. Engine.prototype.isQueryResultAvailable = function (query) {
  11957. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11958. };
  11959. Engine.prototype.getQueryResult = function (query) {
  11960. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11961. };
  11962. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11963. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11964. this._gl.beginQuery(glAlgorithm, query);
  11965. return this;
  11966. };
  11967. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11968. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11969. this._gl.endQuery(glAlgorithm);
  11970. return this;
  11971. };
  11972. /* Time queries */
  11973. Engine.prototype._createTimeQuery = function () {
  11974. var timerQuery = this._caps.timerQuery;
  11975. if (timerQuery.createQueryEXT) {
  11976. return timerQuery.createQueryEXT();
  11977. }
  11978. return this.createQuery();
  11979. };
  11980. Engine.prototype._deleteTimeQuery = function (query) {
  11981. var timerQuery = this._caps.timerQuery;
  11982. if (timerQuery.deleteQueryEXT) {
  11983. timerQuery.deleteQueryEXT(query);
  11984. return;
  11985. }
  11986. this.deleteQuery(query);
  11987. };
  11988. Engine.prototype._getTimeQueryResult = function (query) {
  11989. var timerQuery = this._caps.timerQuery;
  11990. if (timerQuery.getQueryObjectEXT) {
  11991. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11992. }
  11993. return this.getQueryResult(query);
  11994. };
  11995. Engine.prototype._getTimeQueryAvailability = function (query) {
  11996. var timerQuery = this._caps.timerQuery;
  11997. if (timerQuery.getQueryObjectEXT) {
  11998. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11999. }
  12000. return this.isQueryResultAvailable(query);
  12001. };
  12002. Engine.prototype.startTimeQuery = function () {
  12003. var timerQuery = this._caps.timerQuery;
  12004. if (!timerQuery) {
  12005. return null;
  12006. }
  12007. var token = new BABYLON._TimeToken();
  12008. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12009. if (this._caps.canUseTimestampForTimerQuery) {
  12010. token._startTimeQuery = this._createTimeQuery();
  12011. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12012. }
  12013. else {
  12014. if (this._currentNonTimestampToken) {
  12015. return this._currentNonTimestampToken;
  12016. }
  12017. token._timeElapsedQuery = this._createTimeQuery();
  12018. if (timerQuery.beginQueryEXT) {
  12019. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12020. }
  12021. else {
  12022. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12023. }
  12024. this._currentNonTimestampToken = token;
  12025. }
  12026. return token;
  12027. };
  12028. Engine.prototype.endTimeQuery = function (token) {
  12029. var timerQuery = this._caps.timerQuery;
  12030. if (!timerQuery || !token) {
  12031. return -1;
  12032. }
  12033. if (this._caps.canUseTimestampForTimerQuery) {
  12034. if (!token._startTimeQuery) {
  12035. return -1;
  12036. }
  12037. if (!token._endTimeQuery) {
  12038. token._endTimeQuery = this._createTimeQuery();
  12039. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12040. }
  12041. }
  12042. else if (!token._timeElapsedQueryEnded) {
  12043. if (!token._timeElapsedQuery) {
  12044. return -1;
  12045. }
  12046. if (timerQuery.endQueryEXT) {
  12047. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12048. }
  12049. else {
  12050. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12051. }
  12052. token._timeElapsedQueryEnded = true;
  12053. }
  12054. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12055. var available = false;
  12056. if (token._endTimeQuery) {
  12057. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12058. }
  12059. else if (token._timeElapsedQuery) {
  12060. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12061. }
  12062. if (available && !disjoint) {
  12063. var result = 0;
  12064. if (this._caps.canUseTimestampForTimerQuery) {
  12065. if (!token._startTimeQuery || !token._endTimeQuery) {
  12066. return -1;
  12067. }
  12068. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12069. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12070. result = timeEnd - timeStart;
  12071. this._deleteTimeQuery(token._startTimeQuery);
  12072. this._deleteTimeQuery(token._endTimeQuery);
  12073. token._startTimeQuery = null;
  12074. token._endTimeQuery = null;
  12075. }
  12076. else {
  12077. if (!token._timeElapsedQuery) {
  12078. return -1;
  12079. }
  12080. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12081. this._deleteTimeQuery(token._timeElapsedQuery);
  12082. token._timeElapsedQuery = null;
  12083. token._timeElapsedQueryEnded = false;
  12084. this._currentNonTimestampToken = null;
  12085. }
  12086. return result;
  12087. }
  12088. return -1;
  12089. };
  12090. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12091. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12092. };
  12093. // Transform feedback
  12094. Engine.prototype.createTransformFeedback = function () {
  12095. return this._gl.createTransformFeedback();
  12096. };
  12097. Engine.prototype.deleteTransformFeedback = function (value) {
  12098. this._gl.deleteTransformFeedback(value);
  12099. };
  12100. Engine.prototype.bindTransformFeedback = function (value) {
  12101. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12102. };
  12103. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12104. if (usePoints === void 0) { usePoints = true; }
  12105. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12106. };
  12107. Engine.prototype.endTransformFeedback = function () {
  12108. this._gl.endTransformFeedback();
  12109. };
  12110. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12111. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12112. };
  12113. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12114. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12115. };
  12116. // Statics
  12117. Engine.isSupported = function () {
  12118. try {
  12119. var tempcanvas = document.createElement("canvas");
  12120. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12121. return gl != null && !!window.WebGLRenderingContext;
  12122. }
  12123. catch (e) {
  12124. return false;
  12125. }
  12126. };
  12127. Engine.Instances = new Array();
  12128. // Const statics
  12129. Engine._ALPHA_DISABLE = 0;
  12130. Engine._ALPHA_ADD = 1;
  12131. Engine._ALPHA_COMBINE = 2;
  12132. Engine._ALPHA_SUBTRACT = 3;
  12133. Engine._ALPHA_MULTIPLY = 4;
  12134. Engine._ALPHA_MAXIMIZED = 5;
  12135. Engine._ALPHA_ONEONE = 6;
  12136. Engine._ALPHA_PREMULTIPLIED = 7;
  12137. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12138. Engine._ALPHA_INTERPOLATE = 9;
  12139. Engine._ALPHA_SCREENMODE = 10;
  12140. Engine._DELAYLOADSTATE_NONE = 0;
  12141. Engine._DELAYLOADSTATE_LOADED = 1;
  12142. Engine._DELAYLOADSTATE_LOADING = 2;
  12143. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12144. Engine._TEXTUREFORMAT_ALPHA = 0;
  12145. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12146. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12147. Engine._TEXTUREFORMAT_RGB = 4;
  12148. Engine._TEXTUREFORMAT_RGBA = 5;
  12149. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12150. Engine._TEXTURETYPE_FLOAT = 1;
  12151. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12152. // Depht or Stencil test Constants.
  12153. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12154. 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.
  12155. 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.
  12156. 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.
  12157. 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.
  12158. 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.
  12159. 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.
  12160. 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.
  12161. // Stencil Actions Constants.
  12162. Engine._KEEP = 0x1E00;
  12163. Engine._REPLACE = 0x1E01;
  12164. Engine._INCR = 0x1E02;
  12165. Engine._DECR = 0x1E03;
  12166. Engine._INVERT = 0x150A;
  12167. Engine._INCR_WRAP = 0x8507;
  12168. Engine._DECR_WRAP = 0x8508;
  12169. // Texture rescaling mode
  12170. Engine._SCALEMODE_FLOOR = 1;
  12171. Engine._SCALEMODE_NEAREST = 2;
  12172. Engine._SCALEMODE_CEILING = 3;
  12173. // Updatable statics so stick with vars here
  12174. Engine.CollisionsEpsilon = 0.001;
  12175. Engine.CodeRepository = "src/";
  12176. Engine.ShadersRepository = "src/Shaders/";
  12177. return Engine;
  12178. }());
  12179. BABYLON.Engine = Engine;
  12180. })(BABYLON || (BABYLON = {}));
  12181. //# sourceMappingURL=babylon.engine.js.map
  12182. var BABYLON;
  12183. (function (BABYLON) {
  12184. /**
  12185. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12186. */
  12187. var Node = /** @class */ (function () {
  12188. /**
  12189. * @constructor
  12190. * @param {string} name - the name and id to be given to this node
  12191. * @param {BABYLON.Scene} the scene this node will be added to
  12192. */
  12193. function Node(name, scene) {
  12194. if (scene === void 0) { scene = null; }
  12195. this.state = "";
  12196. this.metadata = null;
  12197. this.doNotSerialize = false;
  12198. this.animations = new Array();
  12199. this._ranges = {};
  12200. this._isEnabled = true;
  12201. this._isReady = true;
  12202. this._currentRenderId = -1;
  12203. this._parentRenderId = -1;
  12204. /**
  12205. * An event triggered when the mesh is disposed.
  12206. * @type {BABYLON.Observable}
  12207. */
  12208. this.onDisposeObservable = new BABYLON.Observable();
  12209. // Behaviors
  12210. this._behaviors = new Array();
  12211. this.name = name;
  12212. this.id = name;
  12213. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12214. this.uniqueId = this._scene.getUniqueId();
  12215. this._initCache();
  12216. }
  12217. Object.defineProperty(Node.prototype, "parent", {
  12218. get: function () {
  12219. return this._parentNode;
  12220. },
  12221. set: function (parent) {
  12222. if (this._parentNode === parent) {
  12223. return;
  12224. }
  12225. if (this._parentNode) {
  12226. var index = this._parentNode._children.indexOf(this);
  12227. if (index !== -1) {
  12228. this._parentNode._children.splice(index, 1);
  12229. }
  12230. }
  12231. this._parentNode = parent;
  12232. if (this._parentNode) {
  12233. if (!this._parentNode._children) {
  12234. this._parentNode._children = new Array();
  12235. }
  12236. this._parentNode._children.push(this);
  12237. }
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Node.prototype.getClassName = function () {
  12243. return "Node";
  12244. };
  12245. Object.defineProperty(Node.prototype, "onDispose", {
  12246. set: function (callback) {
  12247. if (this._onDisposeObserver) {
  12248. this.onDisposeObservable.remove(this._onDisposeObserver);
  12249. }
  12250. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12251. },
  12252. enumerable: true,
  12253. configurable: true
  12254. });
  12255. Node.prototype.getScene = function () {
  12256. return this._scene;
  12257. };
  12258. Node.prototype.getEngine = function () {
  12259. return this._scene.getEngine();
  12260. };
  12261. Node.prototype.addBehavior = function (behavior) {
  12262. var index = this._behaviors.indexOf(behavior);
  12263. if (index !== -1) {
  12264. return this;
  12265. }
  12266. behavior.attach(this);
  12267. this._behaviors.push(behavior);
  12268. return this;
  12269. };
  12270. Node.prototype.removeBehavior = function (behavior) {
  12271. var index = this._behaviors.indexOf(behavior);
  12272. if (index === -1) {
  12273. return this;
  12274. }
  12275. this._behaviors[index].detach();
  12276. this._behaviors.splice(index, 1);
  12277. return this;
  12278. };
  12279. Object.defineProperty(Node.prototype, "behaviors", {
  12280. get: function () {
  12281. return this._behaviors;
  12282. },
  12283. enumerable: true,
  12284. configurable: true
  12285. });
  12286. Node.prototype.getBehaviorByName = function (name) {
  12287. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12288. var behavior = _a[_i];
  12289. if (behavior.name === name) {
  12290. return behavior;
  12291. }
  12292. }
  12293. return null;
  12294. };
  12295. // override it in derived class
  12296. Node.prototype.getWorldMatrix = function () {
  12297. return BABYLON.Matrix.Identity();
  12298. };
  12299. // override it in derived class if you add new variables to the cache
  12300. // and call the parent class method
  12301. Node.prototype._initCache = function () {
  12302. this._cache = {};
  12303. this._cache.parent = undefined;
  12304. };
  12305. Node.prototype.updateCache = function (force) {
  12306. if (!force && this.isSynchronized())
  12307. return;
  12308. this._cache.parent = this.parent;
  12309. this._updateCache();
  12310. };
  12311. // override it in derived class if you add new variables to the cache
  12312. // and call the parent class method if !ignoreParentClass
  12313. Node.prototype._updateCache = function (ignoreParentClass) {
  12314. };
  12315. // override it in derived class if you add new variables to the cache
  12316. Node.prototype._isSynchronized = function () {
  12317. return true;
  12318. };
  12319. Node.prototype._markSyncedWithParent = function () {
  12320. if (this.parent) {
  12321. this._parentRenderId = this.parent._currentRenderId;
  12322. }
  12323. };
  12324. Node.prototype.isSynchronizedWithParent = function () {
  12325. if (!this.parent) {
  12326. return true;
  12327. }
  12328. if (this._parentRenderId !== this.parent._currentRenderId) {
  12329. return false;
  12330. }
  12331. return this.parent.isSynchronized();
  12332. };
  12333. Node.prototype.isSynchronized = function (updateCache) {
  12334. var check = this.hasNewParent();
  12335. check = check || !this.isSynchronizedWithParent();
  12336. check = check || !this._isSynchronized();
  12337. if (updateCache)
  12338. this.updateCache(true);
  12339. return !check;
  12340. };
  12341. Node.prototype.hasNewParent = function (update) {
  12342. if (this._cache.parent === this.parent)
  12343. return false;
  12344. if (update)
  12345. this._cache.parent = this.parent;
  12346. return true;
  12347. };
  12348. /**
  12349. * Is this node ready to be used/rendered
  12350. * @return {boolean} is it ready
  12351. */
  12352. Node.prototype.isReady = function () {
  12353. return this._isReady;
  12354. };
  12355. /**
  12356. * Is this node enabled.
  12357. * If the node has a parent and is enabled, the parent will be inspected as well.
  12358. * @return {boolean} whether this node (and its parent) is enabled.
  12359. * @see setEnabled
  12360. */
  12361. Node.prototype.isEnabled = function () {
  12362. if (!this._isEnabled) {
  12363. return false;
  12364. }
  12365. if (this.parent) {
  12366. return this.parent.isEnabled();
  12367. }
  12368. return true;
  12369. };
  12370. /**
  12371. * Set the enabled state of this node.
  12372. * @param {boolean} value - the new enabled state
  12373. * @see isEnabled
  12374. */
  12375. Node.prototype.setEnabled = function (value) {
  12376. this._isEnabled = value;
  12377. };
  12378. /**
  12379. * Is this node a descendant of the given node.
  12380. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12381. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12382. * @see parent
  12383. */
  12384. Node.prototype.isDescendantOf = function (ancestor) {
  12385. if (this.parent) {
  12386. if (this.parent === ancestor) {
  12387. return true;
  12388. }
  12389. return this.parent.isDescendantOf(ancestor);
  12390. }
  12391. return false;
  12392. };
  12393. /**
  12394. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12395. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12396. * @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.
  12397. * @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.
  12398. */
  12399. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12400. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12401. if (!this._children) {
  12402. return;
  12403. }
  12404. for (var index = 0; index < this._children.length; index++) {
  12405. var item = this._children[index];
  12406. if (!predicate || predicate(item)) {
  12407. results.push(item);
  12408. }
  12409. if (!directDescendantsOnly) {
  12410. item._getDescendants(results, false, predicate);
  12411. }
  12412. }
  12413. };
  12414. /**
  12415. * Will return all nodes that have this node as ascendant.
  12416. * @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.
  12417. * @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.
  12418. * @return {BABYLON.Node[]} all children nodes of all types.
  12419. */
  12420. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12421. var results = new Array();
  12422. this._getDescendants(results, directDescendantsOnly, predicate);
  12423. return results;
  12424. };
  12425. /**
  12426. * Get all child-meshes of this node.
  12427. */
  12428. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12429. var results = [];
  12430. this._getDescendants(results, directDecendantsOnly, function (node) {
  12431. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12432. });
  12433. return results;
  12434. };
  12435. /**
  12436. * Get all direct children of this node.
  12437. */
  12438. Node.prototype.getChildren = function (predicate) {
  12439. return this.getDescendants(true, predicate);
  12440. };
  12441. Node.prototype._setReady = function (state) {
  12442. if (state === this._isReady) {
  12443. return;
  12444. }
  12445. if (!state) {
  12446. this._isReady = false;
  12447. return;
  12448. }
  12449. this._isReady = true;
  12450. if (this.onReady) {
  12451. this.onReady(this);
  12452. }
  12453. };
  12454. Node.prototype.getAnimationByName = function (name) {
  12455. for (var i = 0; i < this.animations.length; i++) {
  12456. var animation = this.animations[i];
  12457. if (animation.name === name) {
  12458. return animation;
  12459. }
  12460. }
  12461. return null;
  12462. };
  12463. Node.prototype.createAnimationRange = function (name, from, to) {
  12464. // check name not already in use
  12465. if (!this._ranges[name]) {
  12466. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12467. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12468. if (this.animations[i]) {
  12469. this.animations[i].createRange(name, from, to);
  12470. }
  12471. }
  12472. }
  12473. };
  12474. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12475. if (deleteFrames === void 0) { deleteFrames = true; }
  12476. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12477. if (this.animations[i]) {
  12478. this.animations[i].deleteRange(name, deleteFrames);
  12479. }
  12480. }
  12481. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12482. };
  12483. Node.prototype.getAnimationRange = function (name) {
  12484. return this._ranges[name];
  12485. };
  12486. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12487. var range = this.getAnimationRange(name);
  12488. if (!range) {
  12489. return;
  12490. }
  12491. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12492. };
  12493. Node.prototype.serializeAnimationRanges = function () {
  12494. var serializationRanges = [];
  12495. for (var name in this._ranges) {
  12496. var localRange = this._ranges[name];
  12497. if (!localRange) {
  12498. continue;
  12499. }
  12500. var range = {};
  12501. range.name = name;
  12502. range.from = localRange.from;
  12503. range.to = localRange.to;
  12504. serializationRanges.push(range);
  12505. }
  12506. return serializationRanges;
  12507. };
  12508. Node.prototype.dispose = function () {
  12509. this.parent = null;
  12510. // Callback
  12511. this.onDisposeObservable.notifyObservers(this);
  12512. this.onDisposeObservable.clear();
  12513. // Behaviors
  12514. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12515. var behavior = _a[_i];
  12516. behavior.detach();
  12517. }
  12518. this._behaviors = [];
  12519. };
  12520. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12521. if (parsedNode.ranges) {
  12522. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12523. var data = parsedNode.ranges[index];
  12524. node.createAnimationRange(data.name, data.from, data.to);
  12525. }
  12526. }
  12527. };
  12528. __decorate([
  12529. BABYLON.serialize()
  12530. ], Node.prototype, "name", void 0);
  12531. __decorate([
  12532. BABYLON.serialize()
  12533. ], Node.prototype, "id", void 0);
  12534. __decorate([
  12535. BABYLON.serialize()
  12536. ], Node.prototype, "uniqueId", void 0);
  12537. __decorate([
  12538. BABYLON.serialize()
  12539. ], Node.prototype, "state", void 0);
  12540. __decorate([
  12541. BABYLON.serialize()
  12542. ], Node.prototype, "metadata", void 0);
  12543. return Node;
  12544. }());
  12545. BABYLON.Node = Node;
  12546. })(BABYLON || (BABYLON = {}));
  12547. //# sourceMappingURL=babylon.node.js.map
  12548. var BABYLON;
  12549. (function (BABYLON) {
  12550. var BoundingSphere = /** @class */ (function () {
  12551. function BoundingSphere(minimum, maximum) {
  12552. this.minimum = minimum;
  12553. this.maximum = maximum;
  12554. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12555. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12556. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12557. this.radius = distance * 0.5;
  12558. this.centerWorld = BABYLON.Vector3.Zero();
  12559. this._update(BABYLON.Matrix.Identity());
  12560. }
  12561. // Methods
  12562. BoundingSphere.prototype._update = function (world) {
  12563. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12564. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12565. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12566. };
  12567. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12568. for (var i = 0; i < 6; i++) {
  12569. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12570. return false;
  12571. }
  12572. return true;
  12573. };
  12574. BoundingSphere.prototype.intersectsPoint = function (point) {
  12575. var x = this.centerWorld.x - point.x;
  12576. var y = this.centerWorld.y - point.y;
  12577. var z = this.centerWorld.z - point.z;
  12578. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12579. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12580. return false;
  12581. return true;
  12582. };
  12583. // Statics
  12584. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12585. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12586. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12587. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12588. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12589. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12590. return false;
  12591. return true;
  12592. };
  12593. return BoundingSphere;
  12594. }());
  12595. BABYLON.BoundingSphere = BoundingSphere;
  12596. })(BABYLON || (BABYLON = {}));
  12597. //# sourceMappingURL=babylon.boundingSphere.js.map
  12598. var BABYLON;
  12599. (function (BABYLON) {
  12600. var BoundingBox = /** @class */ (function () {
  12601. function BoundingBox(minimum, maximum) {
  12602. this.minimum = minimum;
  12603. this.maximum = maximum;
  12604. this.vectors = new Array();
  12605. this.vectorsWorld = new Array();
  12606. // Bounding vectors
  12607. this.vectors.push(this.minimum.clone());
  12608. this.vectors.push(this.maximum.clone());
  12609. this.vectors.push(this.minimum.clone());
  12610. this.vectors[2].x = this.maximum.x;
  12611. this.vectors.push(this.minimum.clone());
  12612. this.vectors[3].y = this.maximum.y;
  12613. this.vectors.push(this.minimum.clone());
  12614. this.vectors[4].z = this.maximum.z;
  12615. this.vectors.push(this.maximum.clone());
  12616. this.vectors[5].z = this.minimum.z;
  12617. this.vectors.push(this.maximum.clone());
  12618. this.vectors[6].x = this.minimum.x;
  12619. this.vectors.push(this.maximum.clone());
  12620. this.vectors[7].y = this.minimum.y;
  12621. // OBB
  12622. this.center = this.maximum.add(this.minimum).scale(0.5);
  12623. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12624. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12625. // World
  12626. for (var index = 0; index < this.vectors.length; index++) {
  12627. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12628. }
  12629. this.minimumWorld = BABYLON.Vector3.Zero();
  12630. this.maximumWorld = BABYLON.Vector3.Zero();
  12631. this.centerWorld = BABYLON.Vector3.Zero();
  12632. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12633. this._update(BABYLON.Matrix.Identity());
  12634. }
  12635. // Methods
  12636. BoundingBox.prototype.getWorldMatrix = function () {
  12637. return this._worldMatrix;
  12638. };
  12639. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12640. this._worldMatrix.copyFrom(matrix);
  12641. return this;
  12642. };
  12643. BoundingBox.prototype._update = function (world) {
  12644. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12645. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12646. for (var index = 0; index < this.vectors.length; index++) {
  12647. var v = this.vectorsWorld[index];
  12648. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12649. if (v.x < this.minimumWorld.x)
  12650. this.minimumWorld.x = v.x;
  12651. if (v.y < this.minimumWorld.y)
  12652. this.minimumWorld.y = v.y;
  12653. if (v.z < this.minimumWorld.z)
  12654. this.minimumWorld.z = v.z;
  12655. if (v.x > this.maximumWorld.x)
  12656. this.maximumWorld.x = v.x;
  12657. if (v.y > this.maximumWorld.y)
  12658. this.maximumWorld.y = v.y;
  12659. if (v.z > this.maximumWorld.z)
  12660. this.maximumWorld.z = v.z;
  12661. }
  12662. // Extend
  12663. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12664. this.extendSizeWorld.scaleInPlace(0.5);
  12665. // OBB
  12666. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12667. this.centerWorld.scaleInPlace(0.5);
  12668. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12669. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12670. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12671. this._worldMatrix = world;
  12672. };
  12673. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12674. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12675. };
  12676. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12677. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12678. };
  12679. BoundingBox.prototype.intersectsPoint = function (point) {
  12680. var delta = -BABYLON.Epsilon;
  12681. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12682. return false;
  12683. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12684. return false;
  12685. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12686. return false;
  12687. return true;
  12688. };
  12689. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12690. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12691. };
  12692. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12693. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12694. return false;
  12695. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12696. return false;
  12697. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12698. return false;
  12699. return true;
  12700. };
  12701. // Statics
  12702. BoundingBox.Intersects = function (box0, box1) {
  12703. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12704. return false;
  12705. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12706. return false;
  12707. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12708. return false;
  12709. return true;
  12710. };
  12711. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12712. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12713. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12714. return (num <= (sphereRadius * sphereRadius));
  12715. };
  12716. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12717. for (var p = 0; p < 6; p++) {
  12718. for (var i = 0; i < 8; i++) {
  12719. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12720. return false;
  12721. }
  12722. }
  12723. }
  12724. return true;
  12725. };
  12726. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12727. for (var p = 0; p < 6; p++) {
  12728. var inCount = 8;
  12729. for (var i = 0; i < 8; i++) {
  12730. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12731. --inCount;
  12732. }
  12733. else {
  12734. break;
  12735. }
  12736. }
  12737. if (inCount === 0)
  12738. return false;
  12739. }
  12740. return true;
  12741. };
  12742. return BoundingBox;
  12743. }());
  12744. BABYLON.BoundingBox = BoundingBox;
  12745. })(BABYLON || (BABYLON = {}));
  12746. //# sourceMappingURL=babylon.boundingBox.js.map
  12747. var BABYLON;
  12748. (function (BABYLON) {
  12749. var computeBoxExtents = function (axis, box) {
  12750. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12751. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12752. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12753. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12754. var r = r0 + r1 + r2;
  12755. return {
  12756. min: p - r,
  12757. max: p + r
  12758. };
  12759. };
  12760. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12761. var axisOverlap = function (axis, box0, box1) {
  12762. var result0 = computeBoxExtents(axis, box0);
  12763. var result1 = computeBoxExtents(axis, box1);
  12764. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12765. };
  12766. var BoundingInfo = /** @class */ (function () {
  12767. function BoundingInfo(minimum, maximum) {
  12768. this.minimum = minimum;
  12769. this.maximum = maximum;
  12770. this._isLocked = false;
  12771. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12772. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12773. }
  12774. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12775. get: function () {
  12776. return this._isLocked;
  12777. },
  12778. set: function (value) {
  12779. this._isLocked = value;
  12780. },
  12781. enumerable: true,
  12782. configurable: true
  12783. });
  12784. // Methods
  12785. BoundingInfo.prototype.update = function (world) {
  12786. if (this._isLocked) {
  12787. return;
  12788. }
  12789. this.boundingBox._update(world);
  12790. this.boundingSphere._update(world);
  12791. };
  12792. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12793. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12794. return false;
  12795. return this.boundingBox.isInFrustum(frustumPlanes);
  12796. };
  12797. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12798. /**
  12799. * Gets the world distance between the min and max points of the bounding box
  12800. */
  12801. get: function () {
  12802. var boundingBox = this.boundingBox;
  12803. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12804. return size.length();
  12805. },
  12806. enumerable: true,
  12807. configurable: true
  12808. });
  12809. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12810. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12811. };
  12812. BoundingInfo.prototype._checkCollision = function (collider) {
  12813. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12814. };
  12815. BoundingInfo.prototype.intersectsPoint = function (point) {
  12816. if (!this.boundingSphere.centerWorld) {
  12817. return false;
  12818. }
  12819. if (!this.boundingSphere.intersectsPoint(point)) {
  12820. return false;
  12821. }
  12822. if (!this.boundingBox.intersectsPoint(point)) {
  12823. return false;
  12824. }
  12825. return true;
  12826. };
  12827. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12828. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12829. return false;
  12830. }
  12831. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12832. return false;
  12833. }
  12834. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12835. return false;
  12836. }
  12837. if (!precise) {
  12838. return true;
  12839. }
  12840. var box0 = this.boundingBox;
  12841. var box1 = boundingInfo.boundingBox;
  12842. if (!axisOverlap(box0.directions[0], box0, box1))
  12843. return false;
  12844. if (!axisOverlap(box0.directions[1], box0, box1))
  12845. return false;
  12846. if (!axisOverlap(box0.directions[2], box0, box1))
  12847. return false;
  12848. if (!axisOverlap(box1.directions[0], box0, box1))
  12849. return false;
  12850. if (!axisOverlap(box1.directions[1], box0, box1))
  12851. return false;
  12852. if (!axisOverlap(box1.directions[2], box0, box1))
  12853. return false;
  12854. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12855. return false;
  12856. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12857. return false;
  12858. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12859. return false;
  12860. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12861. return false;
  12862. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12863. return false;
  12864. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12865. return false;
  12866. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12867. return false;
  12868. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12869. return false;
  12870. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12871. return false;
  12872. return true;
  12873. };
  12874. return BoundingInfo;
  12875. }());
  12876. BABYLON.BoundingInfo = BoundingInfo;
  12877. })(BABYLON || (BABYLON = {}));
  12878. //# sourceMappingURL=babylon.boundingInfo.js.map
  12879. var BABYLON;
  12880. (function (BABYLON) {
  12881. var AbstractMesh = /** @class */ (function (_super) {
  12882. __extends(AbstractMesh, _super);
  12883. // Constructor
  12884. function AbstractMesh(name, scene) {
  12885. if (scene === void 0) { scene = null; }
  12886. var _this = _super.call(this, name, scene) || this;
  12887. _this._facetNb = 0; // facet number
  12888. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12889. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12890. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12891. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12892. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12893. _this._subDiv = {
  12894. max: 1,
  12895. X: 1,
  12896. Y: 1,
  12897. Z: 1
  12898. };
  12899. // Normal matrix
  12900. _this._nonUniformScaling = false;
  12901. // Events
  12902. /**
  12903. * An event triggered when this mesh collides with another one
  12904. * @type {BABYLON.Observable}
  12905. */
  12906. _this.onCollideObservable = new BABYLON.Observable();
  12907. /**
  12908. * An event triggered when the collision's position changes
  12909. * @type {BABYLON.Observable}
  12910. */
  12911. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12912. /**
  12913. * An event triggered after the world matrix is updated
  12914. * @type {BABYLON.Observable}
  12915. */
  12916. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12917. /**
  12918. * An event triggered when material is changed
  12919. * @type {BABYLON.Observable}
  12920. */
  12921. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12922. // Properties
  12923. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12924. _this.position = BABYLON.Vector3.Zero();
  12925. /**
  12926. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12927. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12928. * or
  12929. * 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.
  12930. * for more info check WebGl documentations
  12931. */
  12932. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12933. /**
  12934. * 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:
  12935. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12936. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12937. * 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.
  12938. */
  12939. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12940. /**
  12941. * 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.
  12942. * The default value is -1 which means don't break the query and wait till the result.
  12943. */
  12944. _this.occlusionRetryCount = -1;
  12945. _this._occlusionInternalRetryCounter = 0;
  12946. _this._isOccluded = false;
  12947. _this._isOcclusionQueryInProgress = false;
  12948. _this._rotation = BABYLON.Vector3.Zero();
  12949. _this._scaling = BABYLON.Vector3.One();
  12950. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12951. _this.visibility = 1.0;
  12952. _this.alphaIndex = Number.MAX_VALUE;
  12953. _this.infiniteDistance = false;
  12954. _this.isVisible = true;
  12955. _this.isPickable = true;
  12956. _this.showBoundingBox = false;
  12957. _this.showSubMeshesBoundingBox = false;
  12958. _this.isBlocker = false;
  12959. _this.enablePointerMoveEvents = false;
  12960. _this.renderingGroupId = 0;
  12961. _this._receiveShadows = false;
  12962. _this.renderOutline = false;
  12963. _this.outlineColor = BABYLON.Color3.Red();
  12964. _this.outlineWidth = 0.02;
  12965. _this.renderOverlay = false;
  12966. _this.overlayColor = BABYLON.Color3.Red();
  12967. _this.overlayAlpha = 0.5;
  12968. _this._hasVertexAlpha = false;
  12969. _this._useVertexColors = true;
  12970. _this._computeBonesUsingShaders = true;
  12971. _this._numBoneInfluencers = 4;
  12972. _this._applyFog = true;
  12973. _this.scalingDeterminant = 1;
  12974. _this.useOctreeForRenderingSelection = true;
  12975. _this.useOctreeForPicking = true;
  12976. _this.useOctreeForCollisions = true;
  12977. _this._layerMask = 0x0FFFFFFF;
  12978. /**
  12979. * True if the mesh must be rendered in any case.
  12980. */
  12981. _this.alwaysSelectAsActiveMesh = false;
  12982. // Collisions
  12983. _this._checkCollisions = false;
  12984. _this._collisionMask = -1;
  12985. _this._collisionGroup = -1;
  12986. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12987. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12988. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12989. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12990. // Edges
  12991. _this.edgesWidth = 1;
  12992. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12993. // Cache
  12994. _this._localWorld = BABYLON.Matrix.Zero();
  12995. _this._worldMatrix = BABYLON.Matrix.Zero();
  12996. _this._absolutePosition = BABYLON.Vector3.Zero();
  12997. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12998. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12999. _this._isDirty = false;
  13000. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13001. _this._postMultiplyPivotMatrix = false;
  13002. _this._isDisposed = false;
  13003. _this._renderId = 0;
  13004. _this._intersectionsInProgress = new Array();
  13005. _this._isWorldMatrixFrozen = false;
  13006. _this._unIndexed = false;
  13007. _this._lightSources = new Array();
  13008. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13009. if (collidedMesh === void 0) { collidedMesh = null; }
  13010. //TODO move this to the collision coordinator!
  13011. if (_this.getScene().workerCollisions)
  13012. newPosition.multiplyInPlace(_this._collider.radius);
  13013. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  13014. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  13015. _this.position.addInPlace(_this._diffPositionForCollisions);
  13016. }
  13017. if (collidedMesh) {
  13018. _this.onCollideObservable.notifyObservers(collidedMesh);
  13019. }
  13020. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13021. };
  13022. _this.getScene().addMesh(_this);
  13023. _this._resyncLightSources();
  13024. return _this;
  13025. }
  13026. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13027. get: function () {
  13028. return AbstractMesh._BILLBOARDMODE_NONE;
  13029. },
  13030. enumerable: true,
  13031. configurable: true
  13032. });
  13033. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13034. get: function () {
  13035. return AbstractMesh._BILLBOARDMODE_X;
  13036. },
  13037. enumerable: true,
  13038. configurable: true
  13039. });
  13040. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13041. get: function () {
  13042. return AbstractMesh._BILLBOARDMODE_Y;
  13043. },
  13044. enumerable: true,
  13045. configurable: true
  13046. });
  13047. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13048. get: function () {
  13049. return AbstractMesh._BILLBOARDMODE_Z;
  13050. },
  13051. enumerable: true,
  13052. configurable: true
  13053. });
  13054. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13055. get: function () {
  13056. return AbstractMesh._BILLBOARDMODE_ALL;
  13057. },
  13058. enumerable: true,
  13059. configurable: true
  13060. });
  13061. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13062. /**
  13063. * Read-only : the number of facets in the mesh
  13064. */
  13065. get: function () {
  13066. return this._facetNb;
  13067. },
  13068. enumerable: true,
  13069. configurable: true
  13070. });
  13071. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13072. /**
  13073. * The number (integer) of subdivisions per axis in the partioning space
  13074. */
  13075. get: function () {
  13076. return this._partitioningSubdivisions;
  13077. },
  13078. set: function (nb) {
  13079. this._partitioningSubdivisions = nb;
  13080. },
  13081. enumerable: true,
  13082. configurable: true
  13083. });
  13084. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13085. /**
  13086. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13087. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13088. */
  13089. get: function () {
  13090. return this._partitioningBBoxRatio;
  13091. },
  13092. set: function (ratio) {
  13093. this._partitioningBBoxRatio = ratio;
  13094. },
  13095. enumerable: true,
  13096. configurable: true
  13097. });
  13098. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13099. /**
  13100. * Read-only boolean : is the feature facetData enabled ?
  13101. */
  13102. get: function () {
  13103. return this._facetDataEnabled;
  13104. },
  13105. enumerable: true,
  13106. configurable: true
  13107. });
  13108. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13109. get: function () {
  13110. return this._nonUniformScaling;
  13111. },
  13112. set: function (value) {
  13113. if (this._nonUniformScaling === value) {
  13114. return;
  13115. }
  13116. this._nonUniformScaling = true;
  13117. this._markSubMeshesAsMiscDirty();
  13118. },
  13119. enumerable: true,
  13120. configurable: true
  13121. });
  13122. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13123. set: function (callback) {
  13124. if (this._onCollideObserver) {
  13125. this.onCollideObservable.remove(this._onCollideObserver);
  13126. }
  13127. this._onCollideObserver = this.onCollideObservable.add(callback);
  13128. },
  13129. enumerable: true,
  13130. configurable: true
  13131. });
  13132. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13133. set: function (callback) {
  13134. if (this._onCollisionPositionChangeObserver) {
  13135. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13136. }
  13137. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13138. },
  13139. enumerable: true,
  13140. configurable: true
  13141. });
  13142. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13143. /**
  13144. * 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.
  13145. */
  13146. get: function () {
  13147. return this._isOccluded;
  13148. },
  13149. set: function (value) {
  13150. this._isOccluded = value;
  13151. },
  13152. enumerable: true,
  13153. configurable: true
  13154. });
  13155. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13156. /**
  13157. * Flag to check the progress status of the query
  13158. */
  13159. get: function () {
  13160. return this._isOcclusionQueryInProgress;
  13161. },
  13162. enumerable: true,
  13163. configurable: true
  13164. });
  13165. Object.defineProperty(AbstractMesh.prototype, "material", {
  13166. get: function () {
  13167. return this._material;
  13168. },
  13169. set: function (value) {
  13170. if (this._material === value) {
  13171. return;
  13172. }
  13173. this._material = value;
  13174. if (this.onMaterialChangedObservable.hasObservers) {
  13175. this.onMaterialChangedObservable.notifyObservers(this);
  13176. }
  13177. if (!this.subMeshes) {
  13178. return;
  13179. }
  13180. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13181. var subMesh = _a[_i];
  13182. subMesh.setEffect(null);
  13183. }
  13184. },
  13185. enumerable: true,
  13186. configurable: true
  13187. });
  13188. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13189. get: function () {
  13190. return this._receiveShadows;
  13191. },
  13192. set: function (value) {
  13193. if (this._receiveShadows === value) {
  13194. return;
  13195. }
  13196. this._receiveShadows = value;
  13197. this._markSubMeshesAsLightDirty();
  13198. },
  13199. enumerable: true,
  13200. configurable: true
  13201. });
  13202. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13203. get: function () {
  13204. return this._hasVertexAlpha;
  13205. },
  13206. set: function (value) {
  13207. if (this._hasVertexAlpha === value) {
  13208. return;
  13209. }
  13210. this._hasVertexAlpha = value;
  13211. this._markSubMeshesAsAttributesDirty();
  13212. },
  13213. enumerable: true,
  13214. configurable: true
  13215. });
  13216. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13217. get: function () {
  13218. return this._useVertexColors;
  13219. },
  13220. set: function (value) {
  13221. if (this._useVertexColors === value) {
  13222. return;
  13223. }
  13224. this._useVertexColors = value;
  13225. this._markSubMeshesAsAttributesDirty();
  13226. },
  13227. enumerable: true,
  13228. configurable: true
  13229. });
  13230. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13231. get: function () {
  13232. return this._computeBonesUsingShaders;
  13233. },
  13234. set: function (value) {
  13235. if (this._computeBonesUsingShaders === value) {
  13236. return;
  13237. }
  13238. this._computeBonesUsingShaders = value;
  13239. this._markSubMeshesAsAttributesDirty();
  13240. },
  13241. enumerable: true,
  13242. configurable: true
  13243. });
  13244. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13245. get: function () {
  13246. return this._numBoneInfluencers;
  13247. },
  13248. set: function (value) {
  13249. if (this._numBoneInfluencers === value) {
  13250. return;
  13251. }
  13252. this._numBoneInfluencers = value;
  13253. this._markSubMeshesAsAttributesDirty();
  13254. },
  13255. enumerable: true,
  13256. configurable: true
  13257. });
  13258. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13259. get: function () {
  13260. return this._applyFog;
  13261. },
  13262. set: function (value) {
  13263. if (this._applyFog === value) {
  13264. return;
  13265. }
  13266. this._applyFog = value;
  13267. this._markSubMeshesAsMiscDirty();
  13268. },
  13269. enumerable: true,
  13270. configurable: true
  13271. });
  13272. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13273. get: function () {
  13274. return this._layerMask;
  13275. },
  13276. set: function (value) {
  13277. if (value === this._layerMask) {
  13278. return;
  13279. }
  13280. this._layerMask = value;
  13281. this._resyncLightSources();
  13282. },
  13283. enumerable: true,
  13284. configurable: true
  13285. });
  13286. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13287. get: function () {
  13288. return this._collisionMask;
  13289. },
  13290. set: function (mask) {
  13291. this._collisionMask = !isNaN(mask) ? mask : -1;
  13292. },
  13293. enumerable: true,
  13294. configurable: true
  13295. });
  13296. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13297. get: function () {
  13298. return this._collisionGroup;
  13299. },
  13300. set: function (mask) {
  13301. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13307. get: function () {
  13308. return null;
  13309. },
  13310. enumerable: true,
  13311. configurable: true
  13312. });
  13313. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13314. get: function () {
  13315. return this._skeleton;
  13316. },
  13317. set: function (value) {
  13318. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13319. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13320. }
  13321. if (value && value.needInitialSkinMatrix) {
  13322. value._registerMeshWithPoseMatrix(this);
  13323. }
  13324. this._skeleton = value;
  13325. if (!this._skeleton) {
  13326. this._bonesTransformMatrices = null;
  13327. }
  13328. this._markSubMeshesAsAttributesDirty();
  13329. },
  13330. enumerable: true,
  13331. configurable: true
  13332. });
  13333. /**
  13334. * Boolean : true if the mesh has been disposed.
  13335. */
  13336. AbstractMesh.prototype.isDisposed = function () {
  13337. return this._isDisposed;
  13338. };
  13339. /**
  13340. * Returns the string "AbstractMesh"
  13341. */
  13342. AbstractMesh.prototype.getClassName = function () {
  13343. return "AbstractMesh";
  13344. };
  13345. /**
  13346. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13347. */
  13348. AbstractMesh.prototype.toString = function (fullDetails) {
  13349. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13350. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13351. if (this._skeleton) {
  13352. ret += ", skeleton: " + this._skeleton.name;
  13353. }
  13354. if (fullDetails) {
  13355. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13356. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13357. }
  13358. return ret;
  13359. };
  13360. AbstractMesh.prototype._rebuild = function () {
  13361. if (this._occlusionQuery) {
  13362. this._occlusionQuery = null;
  13363. }
  13364. if (this._edgesRenderer) {
  13365. this._edgesRenderer._rebuild();
  13366. }
  13367. if (!this.subMeshes) {
  13368. return;
  13369. }
  13370. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13371. var subMesh = _a[_i];
  13372. subMesh._rebuild();
  13373. }
  13374. };
  13375. AbstractMesh.prototype._resyncLightSources = function () {
  13376. this._lightSources.length = 0;
  13377. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13378. var light = _a[_i];
  13379. if (!light.isEnabled()) {
  13380. continue;
  13381. }
  13382. if (light.canAffectMesh(this)) {
  13383. this._lightSources.push(light);
  13384. }
  13385. }
  13386. this._markSubMeshesAsLightDirty();
  13387. };
  13388. AbstractMesh.prototype._resyncLighSource = function (light) {
  13389. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13390. var index = this._lightSources.indexOf(light);
  13391. if (index === -1) {
  13392. if (!isIn) {
  13393. return;
  13394. }
  13395. this._lightSources.push(light);
  13396. }
  13397. else {
  13398. if (isIn) {
  13399. return;
  13400. }
  13401. this._lightSources.splice(index, 1);
  13402. }
  13403. this._markSubMeshesAsLightDirty();
  13404. };
  13405. AbstractMesh.prototype._removeLightSource = function (light) {
  13406. var index = this._lightSources.indexOf(light);
  13407. if (index === -1) {
  13408. return;
  13409. }
  13410. this._lightSources.splice(index, 1);
  13411. };
  13412. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  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. if (subMesh._materialDefines) {
  13419. func(subMesh._materialDefines);
  13420. }
  13421. }
  13422. };
  13423. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13424. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13425. };
  13426. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13427. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13428. };
  13429. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13430. if (!this.subMeshes) {
  13431. return;
  13432. }
  13433. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13434. var subMesh = _a[_i];
  13435. var material = subMesh.getMaterial();
  13436. if (material) {
  13437. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13438. }
  13439. }
  13440. };
  13441. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13442. /**
  13443. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13444. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13445. * Default : (0.0, 0.0, 0.0)
  13446. */
  13447. get: function () {
  13448. return this._rotation;
  13449. },
  13450. set: function (newRotation) {
  13451. this._rotation = newRotation;
  13452. },
  13453. enumerable: true,
  13454. configurable: true
  13455. });
  13456. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13457. /**
  13458. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13459. * Default : (1.0, 1.0, 1.0)
  13460. */
  13461. get: function () {
  13462. return this._scaling;
  13463. },
  13464. set: function (newScaling) {
  13465. this._scaling = newScaling;
  13466. if (this.physicsImpostor) {
  13467. this.physicsImpostor.forceUpdate();
  13468. }
  13469. },
  13470. enumerable: true,
  13471. configurable: true
  13472. });
  13473. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13474. /**
  13475. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13476. * It's null by default.
  13477. * 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)
  13478. */
  13479. get: function () {
  13480. return this._rotationQuaternion;
  13481. },
  13482. set: function (quaternion) {
  13483. this._rotationQuaternion = quaternion;
  13484. //reset the rotation vector.
  13485. if (quaternion && this.rotation.length()) {
  13486. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13487. }
  13488. },
  13489. enumerable: true,
  13490. configurable: true
  13491. });
  13492. // Methods
  13493. /**
  13494. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13495. * Returns the AbstractMesh.
  13496. */
  13497. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13498. this._poseMatrix.copyFrom(matrix);
  13499. return this;
  13500. };
  13501. /**
  13502. * Returns the mesh Pose matrix.
  13503. * Returned object : Matrix
  13504. */
  13505. AbstractMesh.prototype.getPoseMatrix = function () {
  13506. return this._poseMatrix;
  13507. };
  13508. /**
  13509. * Disables the mesh edger rendering mode.
  13510. * Returns the AbstractMesh.
  13511. */
  13512. AbstractMesh.prototype.disableEdgesRendering = function () {
  13513. if (this._edgesRenderer) {
  13514. this._edgesRenderer.dispose();
  13515. this._edgesRenderer = null;
  13516. }
  13517. return this;
  13518. };
  13519. /**
  13520. * Enables the edge rendering mode on the mesh.
  13521. * This mode makes the mesh edges visible.
  13522. * Returns the AbstractMesh.
  13523. */
  13524. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13525. if (epsilon === void 0) { epsilon = 0.95; }
  13526. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13527. this.disableEdgesRendering();
  13528. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13529. return this;
  13530. };
  13531. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13532. /**
  13533. * Returns true if the mesh is blocked. Used by the class Mesh.
  13534. * Returns the boolean `false` by default.
  13535. */
  13536. get: function () {
  13537. return false;
  13538. },
  13539. enumerable: true,
  13540. configurable: true
  13541. });
  13542. /**
  13543. * Returns the mesh itself by default, used by the class Mesh.
  13544. * Returned type : AbstractMesh
  13545. */
  13546. AbstractMesh.prototype.getLOD = function (camera) {
  13547. return this;
  13548. };
  13549. /**
  13550. * Returns 0 by default, used by the class Mesh.
  13551. * Returns an integer.
  13552. */
  13553. AbstractMesh.prototype.getTotalVertices = function () {
  13554. return 0;
  13555. };
  13556. /**
  13557. * Returns null by default, used by the class Mesh.
  13558. * Returned type : integer array
  13559. */
  13560. AbstractMesh.prototype.getIndices = function () {
  13561. return null;
  13562. };
  13563. /**
  13564. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13565. * Returned type : float array or Float32Array
  13566. */
  13567. AbstractMesh.prototype.getVerticesData = function (kind) {
  13568. return null;
  13569. };
  13570. /**
  13571. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13572. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13573. * The `data` are either a numeric array either a Float32Array.
  13574. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13575. * 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).
  13576. * Note that a new underlying VertexBuffer object is created each call.
  13577. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13578. *
  13579. * Possible `kind` values :
  13580. * - BABYLON.VertexBuffer.PositionKind
  13581. * - BABYLON.VertexBuffer.UVKind
  13582. * - BABYLON.VertexBuffer.UV2Kind
  13583. * - BABYLON.VertexBuffer.UV3Kind
  13584. * - BABYLON.VertexBuffer.UV4Kind
  13585. * - BABYLON.VertexBuffer.UV5Kind
  13586. * - BABYLON.VertexBuffer.UV6Kind
  13587. * - BABYLON.VertexBuffer.ColorKind
  13588. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13589. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13590. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13591. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13592. *
  13593. * Returns the Mesh.
  13594. */
  13595. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13596. return this;
  13597. };
  13598. /**
  13599. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13600. * If the mesh has no geometry, it is simply returned as it is.
  13601. * The `data` are either a numeric array either a Float32Array.
  13602. * No new underlying VertexBuffer object is created.
  13603. * 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.
  13604. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13605. *
  13606. * Possible `kind` values :
  13607. * - BABYLON.VertexBuffer.PositionKind
  13608. * - BABYLON.VertexBuffer.UVKind
  13609. * - BABYLON.VertexBuffer.UV2Kind
  13610. * - BABYLON.VertexBuffer.UV3Kind
  13611. * - BABYLON.VertexBuffer.UV4Kind
  13612. * - BABYLON.VertexBuffer.UV5Kind
  13613. * - BABYLON.VertexBuffer.UV6Kind
  13614. * - BABYLON.VertexBuffer.ColorKind
  13615. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13616. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13617. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13618. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13619. *
  13620. * Returns the Mesh.
  13621. */
  13622. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13623. return this;
  13624. };
  13625. /**
  13626. * Sets the mesh indices.
  13627. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13628. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13629. * This method creates a new index buffer each call.
  13630. * Returns the Mesh.
  13631. */
  13632. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13633. return this;
  13634. };
  13635. /** Returns false by default, used by the class Mesh.
  13636. * Returns a boolean
  13637. */
  13638. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13639. return false;
  13640. };
  13641. /**
  13642. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13643. * Returns a BoundingInfo
  13644. */
  13645. AbstractMesh.prototype.getBoundingInfo = function () {
  13646. if (this._masterMesh) {
  13647. return this._masterMesh.getBoundingInfo();
  13648. }
  13649. if (!this._boundingInfo) {
  13650. this._updateBoundingInfo();
  13651. }
  13652. return this._boundingInfo;
  13653. };
  13654. /**
  13655. * Sets a mesh new object BoundingInfo.
  13656. * Returns the AbstractMesh.
  13657. */
  13658. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13659. this._boundingInfo = boundingInfo;
  13660. return this;
  13661. };
  13662. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13663. get: function () {
  13664. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13665. },
  13666. enumerable: true,
  13667. configurable: true
  13668. });
  13669. AbstractMesh.prototype._preActivate = function () {
  13670. };
  13671. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13672. };
  13673. AbstractMesh.prototype._activate = function (renderId) {
  13674. this._renderId = renderId;
  13675. };
  13676. /**
  13677. * Returns the latest update of the World matrix
  13678. * Returns a Matrix.
  13679. */
  13680. AbstractMesh.prototype.getWorldMatrix = function () {
  13681. if (this._masterMesh) {
  13682. return this._masterMesh.getWorldMatrix();
  13683. }
  13684. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13685. this.computeWorldMatrix();
  13686. }
  13687. return this._worldMatrix;
  13688. };
  13689. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13690. /**
  13691. * Returns directly the latest state of the mesh World matrix.
  13692. * A Matrix is returned.
  13693. */
  13694. get: function () {
  13695. return this._worldMatrix;
  13696. },
  13697. enumerable: true,
  13698. configurable: true
  13699. });
  13700. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13701. /**
  13702. * Returns the current mesh absolute position.
  13703. * Retuns a Vector3.
  13704. */
  13705. get: function () {
  13706. return this._absolutePosition;
  13707. },
  13708. enumerable: true,
  13709. configurable: true
  13710. });
  13711. /**
  13712. * Prevents the World matrix to be computed any longer.
  13713. * Returns the AbstractMesh.
  13714. */
  13715. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13716. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13717. this.computeWorldMatrix(true);
  13718. this._isWorldMatrixFrozen = true;
  13719. return this;
  13720. };
  13721. /**
  13722. * Allows back the World matrix computation.
  13723. * Returns the AbstractMesh.
  13724. */
  13725. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13726. this._isWorldMatrixFrozen = false;
  13727. this.computeWorldMatrix(true);
  13728. return this;
  13729. };
  13730. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13731. /**
  13732. * True if the World matrix has been frozen.
  13733. * Returns a boolean.
  13734. */
  13735. get: function () {
  13736. return this._isWorldMatrixFrozen;
  13737. },
  13738. enumerable: true,
  13739. configurable: true
  13740. });
  13741. /**
  13742. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13743. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13744. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13745. * The passed axis is also normalized.
  13746. * Returns the AbstractMesh.
  13747. */
  13748. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13749. axis.normalize();
  13750. if (!this.rotationQuaternion) {
  13751. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13752. this.rotation = BABYLON.Vector3.Zero();
  13753. }
  13754. var rotationQuaternion;
  13755. if (!space || space === BABYLON.Space.LOCAL) {
  13756. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13757. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13758. }
  13759. else {
  13760. if (this.parent) {
  13761. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13762. invertParentWorldMatrix.invert();
  13763. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13764. }
  13765. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13766. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13767. }
  13768. return this;
  13769. };
  13770. /**
  13771. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13772. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13773. * The passed axis is also normalized.
  13774. * Returns the AbstractMesh.
  13775. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13776. */
  13777. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13778. axis.normalize();
  13779. if (!this.rotationQuaternion) {
  13780. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13781. this.rotation.copyFromFloats(0, 0, 0);
  13782. }
  13783. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13784. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13785. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13786. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13787. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13788. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13789. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13790. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13791. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13792. return this;
  13793. };
  13794. /**
  13795. * Translates the mesh along the axis vector for the passed distance in the given space.
  13796. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13797. * Returns the AbstractMesh.
  13798. */
  13799. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13800. var displacementVector = axis.scale(distance);
  13801. if (!space || space === BABYLON.Space.LOCAL) {
  13802. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13803. this.setPositionWithLocalVector(tempV3);
  13804. }
  13805. else {
  13806. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13807. }
  13808. return this;
  13809. };
  13810. /**
  13811. * Adds a rotation step to the mesh current rotation.
  13812. * x, y, z are Euler angles expressed in radians.
  13813. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13814. * This means this rotation is made in the mesh local space only.
  13815. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13816. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13817. * ```javascript
  13818. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13819. * ```
  13820. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13821. * 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.
  13822. * Returns the AbstractMesh.
  13823. */
  13824. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13825. var rotationQuaternion;
  13826. if (this.rotationQuaternion) {
  13827. rotationQuaternion = this.rotationQuaternion;
  13828. }
  13829. else {
  13830. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13831. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13832. }
  13833. var accumulation = BABYLON.Tmp.Quaternion[0];
  13834. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13835. rotationQuaternion.multiplyInPlace(accumulation);
  13836. if (!this.rotationQuaternion) {
  13837. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13838. }
  13839. return this;
  13840. };
  13841. /**
  13842. * Retuns the mesh absolute position in the World.
  13843. * Returns a Vector3.
  13844. */
  13845. AbstractMesh.prototype.getAbsolutePosition = function () {
  13846. this.computeWorldMatrix();
  13847. return this._absolutePosition;
  13848. };
  13849. /**
  13850. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13851. * Returns the AbstractMesh.
  13852. */
  13853. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13854. if (!absolutePosition) {
  13855. return this;
  13856. }
  13857. var absolutePositionX;
  13858. var absolutePositionY;
  13859. var absolutePositionZ;
  13860. if (absolutePosition.x === undefined) {
  13861. if (arguments.length < 3) {
  13862. return this;
  13863. }
  13864. absolutePositionX = arguments[0];
  13865. absolutePositionY = arguments[1];
  13866. absolutePositionZ = arguments[2];
  13867. }
  13868. else {
  13869. absolutePositionX = absolutePosition.x;
  13870. absolutePositionY = absolutePosition.y;
  13871. absolutePositionZ = absolutePosition.z;
  13872. }
  13873. if (this.parent) {
  13874. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13875. invertParentWorldMatrix.invert();
  13876. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13877. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13878. }
  13879. else {
  13880. this.position.x = absolutePositionX;
  13881. this.position.y = absolutePositionY;
  13882. this.position.z = absolutePositionZ;
  13883. }
  13884. return this;
  13885. };
  13886. // ================================== Point of View Movement =================================
  13887. /**
  13888. * Perform relative position change from the point of view of behind the front of the mesh.
  13889. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13890. * Supports definition of mesh facing forward or backward.
  13891. * @param {number} amountRight
  13892. * @param {number} amountUp
  13893. * @param {number} amountForward
  13894. *
  13895. * Returns the AbstractMesh.
  13896. */
  13897. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13898. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13899. return this;
  13900. };
  13901. /**
  13902. * Calculate relative position change from the point of view of behind the front of the mesh.
  13903. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13904. * Supports definition of mesh facing forward or backward.
  13905. * @param {number} amountRight
  13906. * @param {number} amountUp
  13907. * @param {number} amountForward
  13908. *
  13909. * Returns a new Vector3.
  13910. */
  13911. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13912. var rotMatrix = new BABYLON.Matrix();
  13913. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13914. rotQuaternion.toRotationMatrix(rotMatrix);
  13915. var translationDelta = BABYLON.Vector3.Zero();
  13916. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13918. return translationDelta;
  13919. };
  13920. // ================================== Point of View Rotation =================================
  13921. /**
  13922. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13923. * Supports definition of mesh facing forward or backward.
  13924. * @param {number} flipBack
  13925. * @param {number} twirlClockwise
  13926. * @param {number} tiltRight
  13927. *
  13928. * Returns the AbstractMesh.
  13929. */
  13930. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13931. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13932. return this;
  13933. };
  13934. /**
  13935. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13936. * Supports definition of mesh facing forward or backward.
  13937. * @param {number} flipBack
  13938. * @param {number} twirlClockwise
  13939. * @param {number} tiltRight
  13940. *
  13941. * Returns a new Vector3.
  13942. */
  13943. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13944. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13945. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13946. };
  13947. /**
  13948. * Sets a new pivot matrix to the mesh.
  13949. * Returns the AbstractMesh.
  13950. */
  13951. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13952. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13953. this._pivotMatrix = matrix.clone();
  13954. this._cache.pivotMatrixUpdated = true;
  13955. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13956. if (this._postMultiplyPivotMatrix) {
  13957. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13958. }
  13959. return this;
  13960. };
  13961. /**
  13962. * Returns the mesh pivot matrix.
  13963. * Default : Identity.
  13964. * A Matrix is returned.
  13965. */
  13966. AbstractMesh.prototype.getPivotMatrix = function () {
  13967. return this._pivotMatrix;
  13968. };
  13969. AbstractMesh.prototype._isSynchronized = function () {
  13970. if (this._isDirty) {
  13971. return false;
  13972. }
  13973. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13974. return false;
  13975. if (this._cache.pivotMatrixUpdated) {
  13976. return false;
  13977. }
  13978. if (this.infiniteDistance) {
  13979. return false;
  13980. }
  13981. if (!this._cache.position.equals(this.position))
  13982. return false;
  13983. if (this.rotationQuaternion) {
  13984. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13985. return false;
  13986. }
  13987. if (!this._cache.rotation.equals(this.rotation))
  13988. return false;
  13989. if (!this._cache.scaling.equals(this.scaling))
  13990. return false;
  13991. return true;
  13992. };
  13993. AbstractMesh.prototype._initCache = function () {
  13994. _super.prototype._initCache.call(this);
  13995. this._cache.localMatrixUpdated = false;
  13996. this._cache.position = BABYLON.Vector3.Zero();
  13997. this._cache.scaling = BABYLON.Vector3.Zero();
  13998. this._cache.rotation = BABYLON.Vector3.Zero();
  13999. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14000. this._cache.billboardMode = -1;
  14001. };
  14002. AbstractMesh.prototype.markAsDirty = function (property) {
  14003. if (property === "rotation") {
  14004. this.rotationQuaternion = null;
  14005. }
  14006. this._currentRenderId = Number.MAX_VALUE;
  14007. this._isDirty = true;
  14008. return this;
  14009. };
  14010. /**
  14011. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14012. */
  14013. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  14014. this.computeWorldMatrix(true);
  14015. var min;
  14016. var max;
  14017. var boundingInfo = this.getBoundingInfo();
  14018. if (!this.subMeshes || !boundingInfo) {
  14019. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14020. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14021. }
  14022. else {
  14023. min = boundingInfo.boundingBox.minimumWorld;
  14024. max = boundingInfo.boundingBox.maximumWorld;
  14025. }
  14026. var descendants = this.getDescendants(false);
  14027. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14028. var descendant = descendants_1[_i];
  14029. var childMesh = descendant;
  14030. childMesh.computeWorldMatrix(true);
  14031. var childBoundingInfo = childMesh.getBoundingInfo();
  14032. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14033. continue;
  14034. }
  14035. var boundingBox = childBoundingInfo.boundingBox;
  14036. var minBox = boundingBox.minimumWorld;
  14037. var maxBox = boundingBox.maximumWorld;
  14038. BABYLON.Tools.CheckExtends(minBox, min, max);
  14039. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14040. }
  14041. return {
  14042. min: min,
  14043. max: max
  14044. };
  14045. };
  14046. /**
  14047. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14048. * Returns the AbstractMesh.
  14049. */
  14050. AbstractMesh.prototype._updateBoundingInfo = function () {
  14051. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14052. this._boundingInfo.update(this.worldMatrixFromCache);
  14053. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14054. return this;
  14055. };
  14056. /**
  14057. * Update a mesh's children BoundingInfo objects only.
  14058. * Returns the AbstractMesh.
  14059. */
  14060. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14061. if (!this.subMeshes) {
  14062. return this;
  14063. }
  14064. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14065. var subMesh = this.subMeshes[subIndex];
  14066. if (!subMesh.IsGlobal) {
  14067. subMesh.updateBoundingInfo(matrix);
  14068. }
  14069. }
  14070. return this;
  14071. };
  14072. /**
  14073. * Computes the mesh World matrix and returns it.
  14074. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14075. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14076. * If the parameter `force`is set to `true`, the actual computation is done.
  14077. * Returns the mesh World Matrix.
  14078. */
  14079. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14080. if (this._isWorldMatrixFrozen) {
  14081. return this._worldMatrix;
  14082. }
  14083. if (!force && this.isSynchronized(true)) {
  14084. return this._worldMatrix;
  14085. }
  14086. this._cache.position.copyFrom(this.position);
  14087. this._cache.scaling.copyFrom(this.scaling);
  14088. this._cache.pivotMatrixUpdated = false;
  14089. this._cache.billboardMode = this.billboardMode;
  14090. this._currentRenderId = this.getScene().getRenderId();
  14091. this._isDirty = false;
  14092. // Scaling
  14093. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14094. // Rotation
  14095. //rotate, if quaternion is set and rotation was used
  14096. if (this.rotationQuaternion) {
  14097. var len = this.rotation.length();
  14098. if (len) {
  14099. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14100. this.rotation.copyFromFloats(0, 0, 0);
  14101. }
  14102. }
  14103. if (this.rotationQuaternion) {
  14104. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14105. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14106. }
  14107. else {
  14108. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14109. this._cache.rotation.copyFrom(this.rotation);
  14110. }
  14111. // Translation
  14112. var camera = this.getScene().activeCamera;
  14113. if (this.infiniteDistance && !this.parent && camera) {
  14114. var cameraWorldMatrix = camera.getWorldMatrix();
  14115. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14116. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14117. }
  14118. else {
  14119. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14120. }
  14121. // Composing transformations
  14122. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14123. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14124. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14125. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14126. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14127. // Need to decompose each rotation here
  14128. var currentPosition = BABYLON.Tmp.Vector3[3];
  14129. if (this.parent && this.parent.getWorldMatrix) {
  14130. if (this._meshToBoneReferal) {
  14131. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14132. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14133. }
  14134. else {
  14135. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14136. }
  14137. }
  14138. else {
  14139. currentPosition.copyFrom(this.position);
  14140. }
  14141. currentPosition.subtractInPlace(camera.globalPosition);
  14142. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14143. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14144. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14145. }
  14146. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14147. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14148. }
  14149. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14150. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14151. }
  14152. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14153. }
  14154. else {
  14155. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14156. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14157. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14158. }
  14159. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14160. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14161. }
  14162. // Local world
  14163. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14164. // Parent
  14165. if (this.parent && this.parent.getWorldMatrix) {
  14166. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14167. if (this._meshToBoneReferal) {
  14168. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14169. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14170. }
  14171. else {
  14172. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14173. }
  14174. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14175. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14176. this._worldMatrix.copyFrom(this._localWorld);
  14177. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14178. }
  14179. else {
  14180. if (this._meshToBoneReferal) {
  14181. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14182. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14183. }
  14184. else {
  14185. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14186. }
  14187. }
  14188. this._markSyncedWithParent();
  14189. }
  14190. else {
  14191. this._worldMatrix.copyFrom(this._localWorld);
  14192. }
  14193. // Post multiply inverse of pivotMatrix
  14194. if (this._postMultiplyPivotMatrix) {
  14195. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14196. }
  14197. // Normal matrix
  14198. if (this.scaling.isNonUniform) {
  14199. this.nonUniformScaling = true;
  14200. }
  14201. else if (this.parent && this.parent._nonUniformScaling) {
  14202. this.nonUniformScaling = this.parent._nonUniformScaling;
  14203. }
  14204. else {
  14205. this.nonUniformScaling = false;
  14206. }
  14207. // Bounding info
  14208. this._updateBoundingInfo();
  14209. // Absolute position
  14210. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14211. // Callbacks
  14212. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14213. if (!this._poseMatrix) {
  14214. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14215. }
  14216. return this._worldMatrix;
  14217. };
  14218. /**
  14219. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14220. * @param func: callback function to add
  14221. *
  14222. * Returns the AbstractMesh.
  14223. */
  14224. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14225. this.onAfterWorldMatrixUpdateObservable.add(func);
  14226. return this;
  14227. };
  14228. /**
  14229. * Removes a registered callback function.
  14230. * Returns the AbstractMesh.
  14231. */
  14232. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14233. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14234. return this;
  14235. };
  14236. /**
  14237. * Sets the mesh position in its local space.
  14238. * Returns the AbstractMesh.
  14239. */
  14240. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14241. this.computeWorldMatrix();
  14242. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14243. return this;
  14244. };
  14245. /**
  14246. * Returns the mesh position in the local space from the current World matrix values.
  14247. * Returns a new Vector3.
  14248. */
  14249. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14250. this.computeWorldMatrix();
  14251. var invLocalWorldMatrix = this._localWorld.clone();
  14252. invLocalWorldMatrix.invert();
  14253. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14254. };
  14255. /**
  14256. * Translates the mesh along the passed Vector3 in its local space.
  14257. * Returns the AbstractMesh.
  14258. */
  14259. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14260. this.computeWorldMatrix(true);
  14261. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14262. return this;
  14263. };
  14264. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14265. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14266. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14267. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14268. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14269. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14270. /// <returns>Mesh oriented towards targetMesh</returns>
  14271. if (yawCor === void 0) { yawCor = 0; }
  14272. if (pitchCor === void 0) { pitchCor = 0; }
  14273. if (rollCor === void 0) { rollCor = 0; }
  14274. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14275. var dv = AbstractMesh._lookAtVectorCache;
  14276. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14277. targetPoint.subtractToRef(pos, dv);
  14278. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14279. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14280. var pitch = Math.atan2(dv.y, len);
  14281. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14282. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14283. return this;
  14284. };
  14285. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14286. this._meshToBoneReferal = affectedMesh;
  14287. this.parent = bone;
  14288. if (bone.getWorldMatrix().determinant() < 0) {
  14289. this.scalingDeterminant *= -1;
  14290. }
  14291. return this;
  14292. };
  14293. AbstractMesh.prototype.detachFromBone = function () {
  14294. if (!this.parent) {
  14295. return this;
  14296. }
  14297. if (this.parent.getWorldMatrix().determinant() < 0) {
  14298. this.scalingDeterminant *= -1;
  14299. }
  14300. this._meshToBoneReferal = null;
  14301. this.parent = null;
  14302. return this;
  14303. };
  14304. /**
  14305. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14306. * A mesh is in the frustum if its bounding box intersects the frustum.
  14307. * Boolean returned.
  14308. */
  14309. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14310. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14311. };
  14312. /**
  14313. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14314. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14315. * Boolean returned.
  14316. */
  14317. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14318. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14319. ;
  14320. };
  14321. /**
  14322. * True if the mesh intersects another mesh or a SolidParticle object.
  14323. * 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)
  14324. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14325. * Returns a boolean.
  14326. */
  14327. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14328. if (precise === void 0) { precise = false; }
  14329. if (!this._boundingInfo || !mesh._boundingInfo) {
  14330. return false;
  14331. }
  14332. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14333. return true;
  14334. }
  14335. if (includeDescendants) {
  14336. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14337. var child = _a[_i];
  14338. if (child.intersectsMesh(mesh, precise, true)) {
  14339. return true;
  14340. }
  14341. }
  14342. }
  14343. return false;
  14344. };
  14345. /**
  14346. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14347. * Returns a boolean.
  14348. */
  14349. AbstractMesh.prototype.intersectsPoint = function (point) {
  14350. if (!this._boundingInfo) {
  14351. return false;
  14352. }
  14353. return this._boundingInfo.intersectsPoint(point);
  14354. };
  14355. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14356. return this.physicsImpostor;
  14357. };
  14358. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14359. if (camera === void 0) { camera = null; }
  14360. if (!camera) {
  14361. camera = this.getScene().activeCamera;
  14362. }
  14363. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14364. };
  14365. /**
  14366. * Returns the distance from the mesh to the active camera.
  14367. * Returns a float.
  14368. */
  14369. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14370. if (camera === void 0) { camera = null; }
  14371. if (!camera) {
  14372. camera = this.getScene().activeCamera;
  14373. }
  14374. return this.absolutePosition.subtract(camera.position).length();
  14375. };
  14376. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14377. if (!this.physicsImpostor) {
  14378. return this;
  14379. }
  14380. this.physicsImpostor.applyImpulse(force, contactPoint);
  14381. return this;
  14382. };
  14383. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14384. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14385. return this;
  14386. }
  14387. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14388. mainPivot: pivot1,
  14389. connectedPivot: pivot2,
  14390. nativeParams: options
  14391. });
  14392. return this;
  14393. };
  14394. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14395. // Collisions
  14396. /**
  14397. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14398. * Default `false`.
  14399. */
  14400. get: function () {
  14401. return this._checkCollisions;
  14402. },
  14403. set: function (collisionEnabled) {
  14404. this._checkCollisions = collisionEnabled;
  14405. if (this.getScene().workerCollisions) {
  14406. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14407. }
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14413. var globalPosition = this.getAbsolutePosition();
  14414. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14415. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14416. if (!this._collider) {
  14417. this._collider = new BABYLON.Collider();
  14418. }
  14419. this._collider.radius = this.ellipsoid;
  14420. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14421. return this;
  14422. };
  14423. // Submeshes octree
  14424. /**
  14425. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14426. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14427. * Returns an Octree of submeshes.
  14428. */
  14429. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14430. if (maxCapacity === void 0) { maxCapacity = 64; }
  14431. if (maxDepth === void 0) { maxDepth = 2; }
  14432. if (!this._submeshesOctree) {
  14433. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14434. }
  14435. this.computeWorldMatrix(true);
  14436. var boundingInfo = this.getBoundingInfo();
  14437. // Update octree
  14438. if (boundingInfo) {
  14439. var bbox = boundingInfo.boundingBox;
  14440. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14441. }
  14442. return this._submeshesOctree;
  14443. };
  14444. // Collisions
  14445. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14446. this._generatePointsArray();
  14447. if (!this._positions) {
  14448. return this;
  14449. }
  14450. // Transformation
  14451. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14452. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14453. subMesh._lastColliderWorldVertices = [];
  14454. subMesh._trianglePlanes = [];
  14455. var start = subMesh.verticesStart;
  14456. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14457. for (var i = start; i < end; i++) {
  14458. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14459. }
  14460. }
  14461. // Collide
  14462. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14463. if (collider.collisionFound) {
  14464. collider.collidedMesh = this;
  14465. }
  14466. return this;
  14467. };
  14468. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14469. var subMeshes;
  14470. var len;
  14471. // Octrees
  14472. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14473. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14474. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14475. len = intersections.length;
  14476. subMeshes = intersections.data;
  14477. }
  14478. else {
  14479. subMeshes = this.subMeshes;
  14480. len = subMeshes.length;
  14481. }
  14482. for (var index = 0; index < len; index++) {
  14483. var subMesh = subMeshes[index];
  14484. // Bounding test
  14485. if (len > 1 && !subMesh._checkCollision(collider))
  14486. continue;
  14487. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14488. }
  14489. return this;
  14490. };
  14491. AbstractMesh.prototype._checkCollision = function (collider) {
  14492. // Bounding box test
  14493. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14494. return this;
  14495. // Transformation matrix
  14496. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14497. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14498. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14499. return this;
  14500. };
  14501. // Picking
  14502. AbstractMesh.prototype._generatePointsArray = function () {
  14503. return false;
  14504. };
  14505. /**
  14506. * Checks if the passed Ray intersects with the mesh.
  14507. * Returns an object PickingInfo.
  14508. */
  14509. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14510. var pickingInfo = new BABYLON.PickingInfo();
  14511. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14512. return pickingInfo;
  14513. }
  14514. if (!this._generatePointsArray()) {
  14515. return pickingInfo;
  14516. }
  14517. var intersectInfo = null;
  14518. // Octrees
  14519. var subMeshes;
  14520. var len;
  14521. if (this._submeshesOctree && this.useOctreeForPicking) {
  14522. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14523. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14524. len = intersections.length;
  14525. subMeshes = intersections.data;
  14526. }
  14527. else {
  14528. subMeshes = this.subMeshes;
  14529. len = subMeshes.length;
  14530. }
  14531. for (var index = 0; index < len; index++) {
  14532. var subMesh = subMeshes[index];
  14533. // Bounding test
  14534. if (len > 1 && !subMesh.canIntersects(ray))
  14535. continue;
  14536. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14537. if (currentIntersectInfo) {
  14538. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14539. intersectInfo = currentIntersectInfo;
  14540. intersectInfo.subMeshId = index;
  14541. if (fastCheck) {
  14542. break;
  14543. }
  14544. }
  14545. }
  14546. }
  14547. if (intersectInfo) {
  14548. // Get picked point
  14549. var world = this.getWorldMatrix();
  14550. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14551. var direction = ray.direction.clone();
  14552. direction = direction.scale(intersectInfo.distance);
  14553. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14554. var pickedPoint = worldOrigin.add(worldDirection);
  14555. // Return result
  14556. pickingInfo.hit = true;
  14557. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14558. pickingInfo.pickedPoint = pickedPoint;
  14559. pickingInfo.pickedMesh = this;
  14560. pickingInfo.bu = intersectInfo.bu || 0;
  14561. pickingInfo.bv = intersectInfo.bv || 0;
  14562. pickingInfo.faceId = intersectInfo.faceId;
  14563. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14564. return pickingInfo;
  14565. }
  14566. return pickingInfo;
  14567. };
  14568. /**
  14569. * Clones the mesh, used by the class Mesh.
  14570. * Just returns `null` for an AbstractMesh.
  14571. */
  14572. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14573. return null;
  14574. };
  14575. /**
  14576. * Disposes all the mesh submeshes.
  14577. * Returns the AbstractMesh.
  14578. */
  14579. AbstractMesh.prototype.releaseSubMeshes = function () {
  14580. if (this.subMeshes) {
  14581. while (this.subMeshes.length) {
  14582. this.subMeshes[0].dispose();
  14583. }
  14584. }
  14585. else {
  14586. this.subMeshes = new Array();
  14587. }
  14588. return this;
  14589. };
  14590. /**
  14591. * Disposes the AbstractMesh.
  14592. * Some internal references are kept for further use.
  14593. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14594. * Returns nothing.
  14595. */
  14596. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14597. var _this = this;
  14598. var index;
  14599. // Action manager
  14600. if (this.actionManager) {
  14601. this.actionManager.dispose();
  14602. this.actionManager = null;
  14603. }
  14604. // Skeleton
  14605. this.skeleton = null;
  14606. // Animations
  14607. this.getScene().stopAnimation(this);
  14608. // Physics
  14609. if (this.physicsImpostor) {
  14610. this.physicsImpostor.dispose();
  14611. }
  14612. // Intersections in progress
  14613. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14614. var other = this._intersectionsInProgress[index];
  14615. var pos = other._intersectionsInProgress.indexOf(this);
  14616. other._intersectionsInProgress.splice(pos, 1);
  14617. }
  14618. this._intersectionsInProgress = [];
  14619. // Lights
  14620. var lights = this.getScene().lights;
  14621. lights.forEach(function (light) {
  14622. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14623. if (meshIndex !== -1) {
  14624. light.includedOnlyMeshes.splice(meshIndex, 1);
  14625. }
  14626. meshIndex = light.excludedMeshes.indexOf(_this);
  14627. if (meshIndex !== -1) {
  14628. light.excludedMeshes.splice(meshIndex, 1);
  14629. }
  14630. // Shadow generators
  14631. var generator = light.getShadowGenerator();
  14632. if (generator) {
  14633. var shadowMap = generator.getShadowMap();
  14634. if (shadowMap && shadowMap.renderList) {
  14635. meshIndex = shadowMap.renderList.indexOf(_this);
  14636. if (meshIndex !== -1) {
  14637. shadowMap.renderList.splice(meshIndex, 1);
  14638. }
  14639. }
  14640. }
  14641. });
  14642. // Edges
  14643. if (this._edgesRenderer) {
  14644. this._edgesRenderer.dispose();
  14645. this._edgesRenderer = null;
  14646. }
  14647. // SubMeshes
  14648. if (this.getClassName() !== "InstancedMesh") {
  14649. this.releaseSubMeshes();
  14650. }
  14651. // Octree
  14652. var sceneOctree = this.getScene().selectionOctree;
  14653. if (sceneOctree) {
  14654. var index = sceneOctree.dynamicContent.indexOf(this);
  14655. if (index !== -1) {
  14656. sceneOctree.dynamicContent.splice(index, 1);
  14657. }
  14658. }
  14659. // Query
  14660. var engine = this.getScene().getEngine();
  14661. if (this._occlusionQuery) {
  14662. this._isOcclusionQueryInProgress = false;
  14663. engine.deleteQuery(this._occlusionQuery);
  14664. this._occlusionQuery = null;
  14665. }
  14666. // Engine
  14667. engine.wipeCaches();
  14668. // Remove from scene
  14669. this.getScene().removeMesh(this);
  14670. if (!doNotRecurse) {
  14671. // Particles
  14672. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14673. if (this.getScene().particleSystems[index].emitter === this) {
  14674. this.getScene().particleSystems[index].dispose();
  14675. index--;
  14676. }
  14677. }
  14678. // Children
  14679. var objects = this.getDescendants(true);
  14680. for (index = 0; index < objects.length; index++) {
  14681. objects[index].dispose();
  14682. }
  14683. }
  14684. else {
  14685. var childMeshes = this.getChildMeshes(true);
  14686. for (index = 0; index < childMeshes.length; index++) {
  14687. var child = childMeshes[index];
  14688. child.parent = null;
  14689. child.computeWorldMatrix(true);
  14690. }
  14691. }
  14692. // facet data
  14693. if (this._facetDataEnabled) {
  14694. this.disableFacetData();
  14695. }
  14696. this.onAfterWorldMatrixUpdateObservable.clear();
  14697. this.onCollideObservable.clear();
  14698. this.onCollisionPositionChangeObservable.clear();
  14699. this._isDisposed = true;
  14700. _super.prototype.dispose.call(this);
  14701. };
  14702. /**
  14703. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14704. * This Vector3 is expressed in the World space.
  14705. */
  14706. AbstractMesh.prototype.getDirection = function (localAxis) {
  14707. var result = BABYLON.Vector3.Zero();
  14708. this.getDirectionToRef(localAxis, result);
  14709. return result;
  14710. };
  14711. /**
  14712. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14713. * localAxis is expressed in the mesh local space.
  14714. * result is computed in the Wordl space from the mesh World matrix.
  14715. * Returns the AbstractMesh.
  14716. */
  14717. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14718. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14719. return this;
  14720. };
  14721. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14722. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14723. if (this.getScene().getRenderId() == 0) {
  14724. this.computeWorldMatrix(true);
  14725. }
  14726. var wm = this.getWorldMatrix();
  14727. if (space == BABYLON.Space.WORLD) {
  14728. var tmat = BABYLON.Tmp.Matrix[0];
  14729. wm.invertToRef(tmat);
  14730. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14731. }
  14732. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14733. this._pivotMatrix.m[12] = -point.x;
  14734. this._pivotMatrix.m[13] = -point.y;
  14735. this._pivotMatrix.m[14] = -point.z;
  14736. this._cache.pivotMatrixUpdated = true;
  14737. return this;
  14738. };
  14739. /**
  14740. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14741. */
  14742. AbstractMesh.prototype.getPivotPoint = function () {
  14743. var point = BABYLON.Vector3.Zero();
  14744. this.getPivotPointToRef(point);
  14745. return point;
  14746. };
  14747. /**
  14748. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14749. * Returns the AbstractMesh.
  14750. */
  14751. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14752. result.x = -this._pivotMatrix.m[12];
  14753. result.y = -this._pivotMatrix.m[13];
  14754. result.z = -this._pivotMatrix.m[14];
  14755. return this;
  14756. };
  14757. /**
  14758. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14759. */
  14760. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14761. var point = BABYLON.Vector3.Zero();
  14762. this.getAbsolutePivotPointToRef(point);
  14763. return point;
  14764. };
  14765. /**
  14766. * Defines the passed mesh as the parent of the current mesh.
  14767. * Returns the AbstractMesh.
  14768. */
  14769. AbstractMesh.prototype.setParent = function (mesh) {
  14770. var parent = mesh;
  14771. if (mesh == null) {
  14772. var rotation = BABYLON.Tmp.Quaternion[0];
  14773. var position = BABYLON.Tmp.Vector3[0];
  14774. var scale = BABYLON.Tmp.Vector3[1];
  14775. this.getWorldMatrix().decompose(scale, rotation, position);
  14776. if (this.rotationQuaternion) {
  14777. this.rotationQuaternion.copyFrom(rotation);
  14778. }
  14779. else {
  14780. rotation.toEulerAnglesToRef(this.rotation);
  14781. }
  14782. this.position.x = position.x;
  14783. this.position.y = position.y;
  14784. this.position.z = position.z;
  14785. }
  14786. else {
  14787. var position = BABYLON.Tmp.Vector3[0];
  14788. var m1 = BABYLON.Tmp.Matrix[0];
  14789. parent.getWorldMatrix().invertToRef(m1);
  14790. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14791. this.position.copyFrom(position);
  14792. }
  14793. this.parent = parent;
  14794. return this;
  14795. };
  14796. /**
  14797. * Adds the passed mesh as a child to the current mesh.
  14798. * Returns the AbstractMesh.
  14799. */
  14800. AbstractMesh.prototype.addChild = function (mesh) {
  14801. mesh.setParent(this);
  14802. return this;
  14803. };
  14804. /**
  14805. * Removes the passed mesh from the current mesh children list.
  14806. * Returns the AbstractMesh.
  14807. */
  14808. AbstractMesh.prototype.removeChild = function (mesh) {
  14809. mesh.setParent(null);
  14810. return this;
  14811. };
  14812. /**
  14813. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14814. * Returns the AbstractMesh.
  14815. */
  14816. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14817. result.x = this._pivotMatrix.m[12];
  14818. result.y = this._pivotMatrix.m[13];
  14819. result.z = this._pivotMatrix.m[14];
  14820. this.getPivotPointToRef(result);
  14821. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14822. return this;
  14823. };
  14824. // Facet data
  14825. /**
  14826. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14827. * Returns the AbstractMesh.
  14828. */
  14829. AbstractMesh.prototype._initFacetData = function () {
  14830. if (!this._facetNormals) {
  14831. this._facetNormals = new Array();
  14832. }
  14833. if (!this._facetPositions) {
  14834. this._facetPositions = new Array();
  14835. }
  14836. if (!this._facetPartitioning) {
  14837. this._facetPartitioning = new Array();
  14838. }
  14839. this._facetNb = this.getIndices().length / 3;
  14840. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14841. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14842. for (var f = 0; f < this._facetNb; f++) {
  14843. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14844. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14845. }
  14846. this._facetDataEnabled = true;
  14847. return this;
  14848. };
  14849. /**
  14850. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14851. * This method can be called within the render loop.
  14852. * 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.
  14853. * Returns the AbstractMesh.
  14854. */
  14855. AbstractMesh.prototype.updateFacetData = function () {
  14856. if (!this._facetDataEnabled) {
  14857. this._initFacetData();
  14858. }
  14859. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14860. var indices = this.getIndices();
  14861. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14862. var bInfo = this.getBoundingInfo();
  14863. if (!bInfo) {
  14864. return this;
  14865. }
  14866. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14867. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14868. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14869. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14870. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14871. this._subDiv.max = this._partitioningSubdivisions;
  14872. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14873. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14874. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14875. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14876. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14877. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14878. // set the parameters for ComputeNormals()
  14879. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14880. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14881. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14882. this._facetParameters.bInfo = bInfo;
  14883. this._facetParameters.bbSize = this._bbSize;
  14884. this._facetParameters.subDiv = this._subDiv;
  14885. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14886. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14887. return this;
  14888. };
  14889. /**
  14890. * Returns the facetLocalNormals array.
  14891. * The normals are expressed in the mesh local space.
  14892. */
  14893. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14894. if (!this._facetNormals) {
  14895. this.updateFacetData();
  14896. }
  14897. return this._facetNormals;
  14898. };
  14899. /**
  14900. * Returns the facetLocalPositions array.
  14901. * The facet positions are expressed in the mesh local space.
  14902. */
  14903. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14904. if (!this._facetPositions) {
  14905. this.updateFacetData();
  14906. }
  14907. return this._facetPositions;
  14908. };
  14909. /**
  14910. * Returns the facetLocalPartioning array.
  14911. */
  14912. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14913. if (!this._facetPartitioning) {
  14914. this.updateFacetData();
  14915. }
  14916. return this._facetPartitioning;
  14917. };
  14918. /**
  14919. * Returns the i-th facet position in the world system.
  14920. * This method allocates a new Vector3 per call.
  14921. */
  14922. AbstractMesh.prototype.getFacetPosition = function (i) {
  14923. var pos = BABYLON.Vector3.Zero();
  14924. this.getFacetPositionToRef(i, pos);
  14925. return pos;
  14926. };
  14927. /**
  14928. * Sets the reference Vector3 with the i-th facet position in the world system.
  14929. * Returns the AbstractMesh.
  14930. */
  14931. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14932. var localPos = (this.getFacetLocalPositions())[i];
  14933. var world = this.getWorldMatrix();
  14934. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14935. return this;
  14936. };
  14937. /**
  14938. * Returns the i-th facet normal in the world system.
  14939. * This method allocates a new Vector3 per call.
  14940. */
  14941. AbstractMesh.prototype.getFacetNormal = function (i) {
  14942. var norm = BABYLON.Vector3.Zero();
  14943. this.getFacetNormalToRef(i, norm);
  14944. return norm;
  14945. };
  14946. /**
  14947. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14948. * Returns the AbstractMesh.
  14949. */
  14950. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14951. var localNorm = (this.getFacetLocalNormals())[i];
  14952. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14953. return this;
  14954. };
  14955. /**
  14956. * 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).
  14957. */
  14958. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14959. var bInfo = this.getBoundingInfo();
  14960. if (!bInfo) {
  14961. return null;
  14962. }
  14963. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14964. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14965. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14966. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14967. return null;
  14968. }
  14969. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14970. };
  14971. /**
  14972. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14973. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14974. * 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.
  14975. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14976. * 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.
  14977. */
  14978. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14979. if (checkFace === void 0) { checkFace = false; }
  14980. if (facing === void 0) { facing = true; }
  14981. var world = this.getWorldMatrix();
  14982. var invMat = BABYLON.Tmp.Matrix[5];
  14983. world.invertToRef(invMat);
  14984. var invVect = BABYLON.Tmp.Vector3[8];
  14985. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14986. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14987. if (projected) {
  14988. // tranform the local computed projected vector to world coordinates
  14989. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14990. }
  14991. return closest;
  14992. };
  14993. /**
  14994. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14995. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14996. * 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.
  14997. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14998. * 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.
  14999. */
  15000. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15001. if (checkFace === void 0) { checkFace = false; }
  15002. if (facing === void 0) { facing = true; }
  15003. var closest = null;
  15004. var tmpx = 0.0;
  15005. var tmpy = 0.0;
  15006. var tmpz = 0.0;
  15007. var d = 0.0; // tmp dot facet normal * facet position
  15008. var t0 = 0.0;
  15009. var projx = 0.0;
  15010. var projy = 0.0;
  15011. var projz = 0.0;
  15012. // Get all the facets in the same partitioning block than (x, y, z)
  15013. var facetPositions = this.getFacetLocalPositions();
  15014. var facetNormals = this.getFacetLocalNormals();
  15015. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15016. if (!facetsInBlock) {
  15017. return null;
  15018. }
  15019. // Get the closest facet to (x, y, z)
  15020. var shortest = Number.MAX_VALUE; // init distance vars
  15021. var tmpDistance = shortest;
  15022. var fib; // current facet in the block
  15023. var norm; // current facet normal
  15024. var p0; // current facet barycenter position
  15025. // loop on all the facets in the current partitioning block
  15026. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15027. fib = facetsInBlock[idx];
  15028. norm = facetNormals[fib];
  15029. p0 = facetPositions[fib];
  15030. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15031. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15032. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15033. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15034. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15035. projx = x + norm.x * t0;
  15036. projy = y + norm.y * t0;
  15037. projz = z + norm.z * t0;
  15038. tmpx = projx - x;
  15039. tmpy = projy - y;
  15040. tmpz = projz - z;
  15041. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15042. if (tmpDistance < shortest) {
  15043. shortest = tmpDistance;
  15044. closest = fib;
  15045. if (projected) {
  15046. projected.x = projx;
  15047. projected.y = projy;
  15048. projected.z = projz;
  15049. }
  15050. }
  15051. }
  15052. }
  15053. return closest;
  15054. };
  15055. /**
  15056. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15057. */
  15058. AbstractMesh.prototype.getFacetDataParameters = function () {
  15059. return this._facetParameters;
  15060. };
  15061. /**
  15062. * Disables the feature FacetData and frees the related memory.
  15063. * Returns the AbstractMesh.
  15064. */
  15065. AbstractMesh.prototype.disableFacetData = function () {
  15066. if (this._facetDataEnabled) {
  15067. this._facetDataEnabled = false;
  15068. this._facetPositions = new Array();
  15069. ;
  15070. this._facetNormals = new Array();
  15071. ;
  15072. this._facetPartitioning = new Array();
  15073. ;
  15074. this._facetParameters = null;
  15075. }
  15076. return this;
  15077. };
  15078. /**
  15079. * Creates new normals data for the mesh.
  15080. * @param updatable.
  15081. */
  15082. AbstractMesh.prototype.createNormals = function (updatable) {
  15083. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15084. var indices = this.getIndices();
  15085. var normals;
  15086. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15087. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15088. }
  15089. else {
  15090. normals = [];
  15091. }
  15092. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15093. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15094. };
  15095. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15096. var engine = this.getEngine();
  15097. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15098. this._isOccluded = false;
  15099. return;
  15100. }
  15101. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15102. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15103. if (isOcclusionQueryAvailable) {
  15104. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15105. this._isOcclusionQueryInProgress = false;
  15106. this._occlusionInternalRetryCounter = 0;
  15107. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15108. }
  15109. else {
  15110. this._occlusionInternalRetryCounter++;
  15111. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15112. this._isOcclusionQueryInProgress = false;
  15113. this._occlusionInternalRetryCounter = 0;
  15114. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15115. // if strict continue the last state of the object.
  15116. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15117. }
  15118. else {
  15119. return;
  15120. }
  15121. }
  15122. }
  15123. var scene = this.getScene();
  15124. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15125. if (!this._occlusionQuery) {
  15126. this._occlusionQuery = engine.createQuery();
  15127. }
  15128. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15129. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15130. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15131. this._isOcclusionQueryInProgress = true;
  15132. };
  15133. // Statics
  15134. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15135. AbstractMesh._BILLBOARDMODE_X = 1;
  15136. AbstractMesh._BILLBOARDMODE_Y = 2;
  15137. AbstractMesh._BILLBOARDMODE_Z = 4;
  15138. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15139. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15140. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15141. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15142. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15143. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15144. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15145. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15146. return AbstractMesh;
  15147. }(BABYLON.Node));
  15148. BABYLON.AbstractMesh = AbstractMesh;
  15149. })(BABYLON || (BABYLON = {}));
  15150. //# sourceMappingURL=babylon.abstractMesh.js.map
  15151. var BABYLON;
  15152. (function (BABYLON) {
  15153. var Light = /** @class */ (function (_super) {
  15154. __extends(Light, _super);
  15155. /**
  15156. * Creates a Light object in the scene.
  15157. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15158. */
  15159. function Light(name, scene) {
  15160. var _this = _super.call(this, name, scene) || this;
  15161. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15162. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15163. _this.intensity = 1.0;
  15164. _this.range = Number.MAX_VALUE;
  15165. /**
  15166. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15167. * of light.
  15168. */
  15169. _this._photometricScale = 1.0;
  15170. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15171. _this._radius = 0.00001;
  15172. _this.renderPriority = 0;
  15173. /**
  15174. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15175. * the current shadow generator.
  15176. */
  15177. _this.shadowEnabled = true;
  15178. _this._excludeWithLayerMask = 0;
  15179. _this._includeOnlyWithLayerMask = 0;
  15180. _this._lightmapMode = 0;
  15181. _this._excludedMeshesIds = new Array();
  15182. _this._includedOnlyMeshesIds = new Array();
  15183. _this.getScene().addLight(_this);
  15184. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15185. _this._buildUniformLayout();
  15186. _this.includedOnlyMeshes = new Array();
  15187. _this.excludedMeshes = new Array();
  15188. _this._resyncMeshes();
  15189. return _this;
  15190. }
  15191. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15192. /**
  15193. * If every light affecting the material is in this lightmapMode,
  15194. * material.lightmapTexture adds or multiplies
  15195. * (depends on material.useLightmapAsShadowmap)
  15196. * after every other light calculations.
  15197. */
  15198. get: function () {
  15199. return Light._LIGHTMAP_DEFAULT;
  15200. },
  15201. enumerable: true,
  15202. configurable: true
  15203. });
  15204. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15205. /**
  15206. * material.lightmapTexture as only diffuse lighting from this light
  15207. * adds pnly specular lighting from this light
  15208. * adds dynamic shadows
  15209. */
  15210. get: function () {
  15211. return Light._LIGHTMAP_SPECULAR;
  15212. },
  15213. enumerable: true,
  15214. configurable: true
  15215. });
  15216. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15217. /**
  15218. * material.lightmapTexture as only lighting
  15219. * no light calculation from this light
  15220. * only adds dynamic shadows from this light
  15221. */
  15222. get: function () {
  15223. return Light._LIGHTMAP_SHADOWSONLY;
  15224. },
  15225. enumerable: true,
  15226. configurable: true
  15227. });
  15228. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15229. /**
  15230. * Each light type uses the default quantity according to its type:
  15231. * point/spot lights use luminous intensity
  15232. * directional lights use illuminance
  15233. */
  15234. get: function () {
  15235. return Light._INTENSITYMODE_AUTOMATIC;
  15236. },
  15237. enumerable: true,
  15238. configurable: true
  15239. });
  15240. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15241. /**
  15242. * lumen (lm)
  15243. */
  15244. get: function () {
  15245. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15246. },
  15247. enumerable: true,
  15248. configurable: true
  15249. });
  15250. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15251. /**
  15252. * candela (lm/sr)
  15253. */
  15254. get: function () {
  15255. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15256. },
  15257. enumerable: true,
  15258. configurable: true
  15259. });
  15260. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15261. /**
  15262. * lux (lm/m^2)
  15263. */
  15264. get: function () {
  15265. return Light._INTENSITYMODE_ILLUMINANCE;
  15266. },
  15267. enumerable: true,
  15268. configurable: true
  15269. });
  15270. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15271. /**
  15272. * nit (cd/m^2)
  15273. */
  15274. get: function () {
  15275. return Light._INTENSITYMODE_LUMINANCE;
  15276. },
  15277. enumerable: true,
  15278. configurable: true
  15279. });
  15280. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15281. /**
  15282. * Light type const id of the point light.
  15283. */
  15284. get: function () {
  15285. return Light._LIGHTTYPEID_POINTLIGHT;
  15286. },
  15287. enumerable: true,
  15288. configurable: true
  15289. });
  15290. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15291. /**
  15292. * Light type const id of the directional light.
  15293. */
  15294. get: function () {
  15295. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15301. /**
  15302. * Light type const id of the spot light.
  15303. */
  15304. get: function () {
  15305. return Light._LIGHTTYPEID_SPOTLIGHT;
  15306. },
  15307. enumerable: true,
  15308. configurable: true
  15309. });
  15310. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15311. /**
  15312. * Light type const id of the hemispheric light.
  15313. */
  15314. get: function () {
  15315. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15316. },
  15317. enumerable: true,
  15318. configurable: true
  15319. });
  15320. Object.defineProperty(Light.prototype, "intensityMode", {
  15321. /**
  15322. * Gets the photometric scale used to interpret the intensity.
  15323. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15324. */
  15325. get: function () {
  15326. return this._intensityMode;
  15327. },
  15328. /**
  15329. * Sets the photometric scale used to interpret the intensity.
  15330. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15331. */
  15332. set: function (value) {
  15333. this._intensityMode = value;
  15334. this._computePhotometricScale();
  15335. },
  15336. enumerable: true,
  15337. configurable: true
  15338. });
  15339. ;
  15340. ;
  15341. Object.defineProperty(Light.prototype, "radius", {
  15342. /**
  15343. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15344. */
  15345. get: function () {
  15346. return this._radius;
  15347. },
  15348. /**
  15349. * sets the light radius used by PBR Materials to simulate soft area lights.
  15350. */
  15351. set: function (value) {
  15352. this._radius = value;
  15353. this._computePhotometricScale();
  15354. },
  15355. enumerable: true,
  15356. configurable: true
  15357. });
  15358. ;
  15359. ;
  15360. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15361. get: function () {
  15362. return this._includedOnlyMeshes;
  15363. },
  15364. set: function (value) {
  15365. this._includedOnlyMeshes = value;
  15366. this._hookArrayForIncludedOnly(value);
  15367. },
  15368. enumerable: true,
  15369. configurable: true
  15370. });
  15371. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15372. get: function () {
  15373. return this._excludedMeshes;
  15374. },
  15375. set: function (value) {
  15376. this._excludedMeshes = value;
  15377. this._hookArrayForExcluded(value);
  15378. },
  15379. enumerable: true,
  15380. configurable: true
  15381. });
  15382. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15383. get: function () {
  15384. return this._excludeWithLayerMask;
  15385. },
  15386. set: function (value) {
  15387. this._excludeWithLayerMask = value;
  15388. this._resyncMeshes();
  15389. },
  15390. enumerable: true,
  15391. configurable: true
  15392. });
  15393. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15394. get: function () {
  15395. return this._includeOnlyWithLayerMask;
  15396. },
  15397. set: function (value) {
  15398. this._includeOnlyWithLayerMask = value;
  15399. this._resyncMeshes();
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. Object.defineProperty(Light.prototype, "lightmapMode", {
  15405. get: function () {
  15406. return this._lightmapMode;
  15407. },
  15408. set: function (value) {
  15409. if (this._lightmapMode === value) {
  15410. return;
  15411. }
  15412. this._lightmapMode = value;
  15413. this._markMeshesAsLightDirty();
  15414. },
  15415. enumerable: true,
  15416. configurable: true
  15417. });
  15418. Light.prototype._buildUniformLayout = function () {
  15419. // Overridden
  15420. };
  15421. /**
  15422. * Returns the string "Light".
  15423. */
  15424. Light.prototype.getClassName = function () {
  15425. return "Light";
  15426. };
  15427. /**
  15428. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15429. */
  15430. Light.prototype.toString = function (fullDetails) {
  15431. var ret = "Name: " + this.name;
  15432. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15433. if (this.animations) {
  15434. for (var i = 0; i < this.animations.length; i++) {
  15435. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15436. }
  15437. }
  15438. if (fullDetails) {
  15439. }
  15440. return ret;
  15441. };
  15442. /**
  15443. * Set the enabled state of this node.
  15444. * @param {boolean} value - the new enabled state
  15445. * @see isEnabled
  15446. */
  15447. Light.prototype.setEnabled = function (value) {
  15448. _super.prototype.setEnabled.call(this, value);
  15449. this._resyncMeshes();
  15450. };
  15451. /**
  15452. * Returns the Light associated shadow generator.
  15453. */
  15454. Light.prototype.getShadowGenerator = function () {
  15455. return this._shadowGenerator;
  15456. };
  15457. /**
  15458. * Returns a Vector3, the absolute light position in the World.
  15459. */
  15460. Light.prototype.getAbsolutePosition = function () {
  15461. return BABYLON.Vector3.Zero();
  15462. };
  15463. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15464. };
  15465. Light.prototype._getWorldMatrix = function () {
  15466. return BABYLON.Matrix.Identity();
  15467. };
  15468. /**
  15469. * Boolean : True if the light will affect the passed mesh.
  15470. */
  15471. Light.prototype.canAffectMesh = function (mesh) {
  15472. if (!mesh) {
  15473. return true;
  15474. }
  15475. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15476. return false;
  15477. }
  15478. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15479. return false;
  15480. }
  15481. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15482. return false;
  15483. }
  15484. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15485. return false;
  15486. }
  15487. return true;
  15488. };
  15489. /**
  15490. * Returns the light World matrix.
  15491. */
  15492. Light.prototype.getWorldMatrix = function () {
  15493. this._currentRenderId = this.getScene().getRenderId();
  15494. var worldMatrix = this._getWorldMatrix();
  15495. if (this.parent && this.parent.getWorldMatrix) {
  15496. if (!this._parentedWorldMatrix) {
  15497. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15498. }
  15499. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15500. this._markSyncedWithParent();
  15501. return this._parentedWorldMatrix;
  15502. }
  15503. return worldMatrix;
  15504. };
  15505. /**
  15506. * Sort function to order lights for rendering.
  15507. * @param a First Light object to compare to second.
  15508. * @param b Second Light object to compare first.
  15509. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15510. */
  15511. Light.compareLightsPriority = function (a, b) {
  15512. //shadow-casting lights have priority over non-shadow-casting lights
  15513. //the renderPrioirty is a secondary sort criterion
  15514. if (a.shadowEnabled !== b.shadowEnabled) {
  15515. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15516. }
  15517. return b.renderPriority - a.renderPriority;
  15518. };
  15519. /**
  15520. * Disposes the light.
  15521. */
  15522. Light.prototype.dispose = function () {
  15523. if (this._shadowGenerator) {
  15524. this._shadowGenerator.dispose();
  15525. this._shadowGenerator = null;
  15526. }
  15527. // Animations
  15528. this.getScene().stopAnimation(this);
  15529. // Remove from meshes
  15530. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15531. var mesh = _a[_i];
  15532. mesh._removeLightSource(this);
  15533. }
  15534. this._uniformBuffer.dispose();
  15535. // Remove from scene
  15536. this.getScene().removeLight(this);
  15537. _super.prototype.dispose.call(this);
  15538. };
  15539. /**
  15540. * Returns the light type ID (integer).
  15541. */
  15542. Light.prototype.getTypeID = function () {
  15543. return 0;
  15544. };
  15545. /**
  15546. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15547. */
  15548. Light.prototype.getScaledIntensity = function () {
  15549. return this._photometricScale * this.intensity;
  15550. };
  15551. /**
  15552. * Returns a new Light object, named "name", from the current one.
  15553. */
  15554. Light.prototype.clone = function (name) {
  15555. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15556. if (!constructor) {
  15557. return null;
  15558. }
  15559. return BABYLON.SerializationHelper.Clone(constructor, this);
  15560. };
  15561. /**
  15562. * Serializes the current light into a Serialization object.
  15563. * Returns the serialized object.
  15564. */
  15565. Light.prototype.serialize = function () {
  15566. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15567. // Type
  15568. serializationObject.type = this.getTypeID();
  15569. // Parent
  15570. if (this.parent) {
  15571. serializationObject.parentId = this.parent.id;
  15572. }
  15573. // Inclusion / exclusions
  15574. if (this.excludedMeshes.length > 0) {
  15575. serializationObject.excludedMeshesIds = [];
  15576. this.excludedMeshes.forEach(function (mesh) {
  15577. serializationObject.excludedMeshesIds.push(mesh.id);
  15578. });
  15579. }
  15580. if (this.includedOnlyMeshes.length > 0) {
  15581. serializationObject.includedOnlyMeshesIds = [];
  15582. this.includedOnlyMeshes.forEach(function (mesh) {
  15583. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15584. });
  15585. }
  15586. // Animations
  15587. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15588. serializationObject.ranges = this.serializeAnimationRanges();
  15589. return serializationObject;
  15590. };
  15591. /**
  15592. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15593. * This new light is named "name" and added to the passed scene.
  15594. */
  15595. Light.GetConstructorFromName = function (type, name, scene) {
  15596. switch (type) {
  15597. case 0:
  15598. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15599. case 1:
  15600. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15601. case 2:
  15602. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15603. case 3:
  15604. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15605. }
  15606. return null;
  15607. };
  15608. /**
  15609. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15610. */
  15611. Light.Parse = function (parsedLight, scene) {
  15612. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15613. if (!constructor) {
  15614. return null;
  15615. }
  15616. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15617. // Inclusion / exclusions
  15618. if (parsedLight.excludedMeshesIds) {
  15619. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15620. }
  15621. if (parsedLight.includedOnlyMeshesIds) {
  15622. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15623. }
  15624. // Parent
  15625. if (parsedLight.parentId) {
  15626. light._waitingParentId = parsedLight.parentId;
  15627. }
  15628. // Animations
  15629. if (parsedLight.animations) {
  15630. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15631. var parsedAnimation = parsedLight.animations[animationIndex];
  15632. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15633. }
  15634. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15635. }
  15636. if (parsedLight.autoAnimate) {
  15637. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15638. }
  15639. return light;
  15640. };
  15641. Light.prototype._hookArrayForExcluded = function (array) {
  15642. var _this = this;
  15643. var oldPush = array.push;
  15644. array.push = function () {
  15645. var items = [];
  15646. for (var _i = 0; _i < arguments.length; _i++) {
  15647. items[_i] = arguments[_i];
  15648. }
  15649. var result = oldPush.apply(array, items);
  15650. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15651. var item = items_1[_a];
  15652. item._resyncLighSource(_this);
  15653. }
  15654. return result;
  15655. };
  15656. var oldSplice = array.splice;
  15657. array.splice = function (index, deleteCount) {
  15658. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15659. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15660. var item = deleted_1[_i];
  15661. item._resyncLighSource(_this);
  15662. }
  15663. return deleted;
  15664. };
  15665. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15666. var item = array_1[_i];
  15667. item._resyncLighSource(this);
  15668. }
  15669. };
  15670. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15671. var _this = this;
  15672. var oldPush = array.push;
  15673. array.push = function () {
  15674. var items = [];
  15675. for (var _i = 0; _i < arguments.length; _i++) {
  15676. items[_i] = arguments[_i];
  15677. }
  15678. var result = oldPush.apply(array, items);
  15679. _this._resyncMeshes();
  15680. return result;
  15681. };
  15682. var oldSplice = array.splice;
  15683. array.splice = function (index, deleteCount) {
  15684. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15685. _this._resyncMeshes();
  15686. return deleted;
  15687. };
  15688. this._resyncMeshes();
  15689. };
  15690. Light.prototype._resyncMeshes = function () {
  15691. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15692. var mesh = _a[_i];
  15693. mesh._resyncLighSource(this);
  15694. }
  15695. };
  15696. Light.prototype._markMeshesAsLightDirty = function () {
  15697. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15698. var mesh = _a[_i];
  15699. if (mesh._lightSources.indexOf(this) !== -1) {
  15700. mesh._markSubMeshesAsLightDirty();
  15701. }
  15702. }
  15703. };
  15704. /**
  15705. * Recomputes the cached photometric scale if needed.
  15706. */
  15707. Light.prototype._computePhotometricScale = function () {
  15708. this._photometricScale = this._getPhotometricScale();
  15709. this.getScene().resetCachedMaterial();
  15710. };
  15711. /**
  15712. * Returns the Photometric Scale according to the light type and intensity mode.
  15713. */
  15714. Light.prototype._getPhotometricScale = function () {
  15715. var photometricScale = 0.0;
  15716. var lightTypeID = this.getTypeID();
  15717. //get photometric mode
  15718. var photometricMode = this.intensityMode;
  15719. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15720. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15721. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15722. }
  15723. else {
  15724. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15725. }
  15726. }
  15727. //compute photometric scale
  15728. switch (lightTypeID) {
  15729. case Light.LIGHTTYPEID_POINTLIGHT:
  15730. case Light.LIGHTTYPEID_SPOTLIGHT:
  15731. switch (photometricMode) {
  15732. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15733. photometricScale = 1.0 / (4.0 * Math.PI);
  15734. break;
  15735. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15736. photometricScale = 1.0;
  15737. break;
  15738. case Light.INTENSITYMODE_LUMINANCE:
  15739. photometricScale = this.radius * this.radius;
  15740. break;
  15741. }
  15742. break;
  15743. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15744. switch (photometricMode) {
  15745. case Light.INTENSITYMODE_ILLUMINANCE:
  15746. photometricScale = 1.0;
  15747. break;
  15748. case Light.INTENSITYMODE_LUMINANCE:
  15749. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15750. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15751. var apexAngleRadians = this.radius;
  15752. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15753. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15754. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15755. photometricScale = solidAngle;
  15756. break;
  15757. }
  15758. break;
  15759. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15760. // No fall off in hemisperic light.
  15761. photometricScale = 1.0;
  15762. break;
  15763. }
  15764. return photometricScale;
  15765. };
  15766. Light.prototype._reorderLightsInScene = function () {
  15767. var scene = this.getScene();
  15768. if (this._renderPriority != 0) {
  15769. scene.requireLightSorting = true;
  15770. }
  15771. this.getScene().sortLightsByPriority();
  15772. };
  15773. //lightmapMode Consts
  15774. Light._LIGHTMAP_DEFAULT = 0;
  15775. Light._LIGHTMAP_SPECULAR = 1;
  15776. Light._LIGHTMAP_SHADOWSONLY = 2;
  15777. // Intensity Mode Consts
  15778. Light._INTENSITYMODE_AUTOMATIC = 0;
  15779. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15780. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15781. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15782. Light._INTENSITYMODE_LUMINANCE = 4;
  15783. // Light types ids const.
  15784. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15785. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15786. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15787. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15788. __decorate([
  15789. BABYLON.serializeAsColor3()
  15790. ], Light.prototype, "diffuse", void 0);
  15791. __decorate([
  15792. BABYLON.serializeAsColor3()
  15793. ], Light.prototype, "specular", void 0);
  15794. __decorate([
  15795. BABYLON.serialize()
  15796. ], Light.prototype, "intensity", void 0);
  15797. __decorate([
  15798. BABYLON.serialize()
  15799. ], Light.prototype, "range", void 0);
  15800. __decorate([
  15801. BABYLON.serialize()
  15802. ], Light.prototype, "intensityMode", null);
  15803. __decorate([
  15804. BABYLON.serialize()
  15805. ], Light.prototype, "radius", null);
  15806. __decorate([
  15807. BABYLON.serialize()
  15808. ], Light.prototype, "_renderPriority", void 0);
  15809. __decorate([
  15810. BABYLON.expandToProperty("_reorderLightsInScene")
  15811. ], Light.prototype, "renderPriority", void 0);
  15812. __decorate([
  15813. BABYLON.serialize()
  15814. ], Light.prototype, "shadowEnabled", void 0);
  15815. __decorate([
  15816. BABYLON.serialize("excludeWithLayerMask")
  15817. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15818. __decorate([
  15819. BABYLON.serialize("includeOnlyWithLayerMask")
  15820. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15821. __decorate([
  15822. BABYLON.serialize("lightmapMode")
  15823. ], Light.prototype, "_lightmapMode", void 0);
  15824. return Light;
  15825. }(BABYLON.Node));
  15826. BABYLON.Light = Light;
  15827. })(BABYLON || (BABYLON = {}));
  15828. //# sourceMappingURL=babylon.light.js.map
  15829. var BABYLON;
  15830. (function (BABYLON) {
  15831. var Camera = /** @class */ (function (_super) {
  15832. __extends(Camera, _super);
  15833. function Camera(name, position, scene) {
  15834. var _this = _super.call(this, name, scene) || this;
  15835. _this.upVector = BABYLON.Vector3.Up();
  15836. _this.orthoLeft = null;
  15837. _this.orthoRight = null;
  15838. _this.orthoBottom = null;
  15839. _this.orthoTop = null;
  15840. _this.fov = 0.8;
  15841. _this.minZ = 1;
  15842. _this.maxZ = 10000.0;
  15843. _this.inertia = 0.9;
  15844. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15845. _this.isIntermediate = false;
  15846. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15847. _this.layerMask = 0x0FFFFFFF;
  15848. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15849. // Camera rig members
  15850. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15851. _this._rigCameras = new Array();
  15852. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15853. _this._skipRendering = false;
  15854. _this.customRenderTargets = new Array();
  15855. // Observables
  15856. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15857. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15858. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15859. _this.onRestoreStateObservable = new BABYLON.Observable();
  15860. // Cache
  15861. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15862. _this._projectionMatrix = new BABYLON.Matrix();
  15863. _this._doNotComputeProjectionMatrix = false;
  15864. _this._postProcesses = new Array();
  15865. _this._transformMatrix = BABYLON.Matrix.Zero();
  15866. _this._activeMeshes = new BABYLON.SmartArray(256);
  15867. _this._globalPosition = BABYLON.Vector3.Zero();
  15868. _this._refreshFrustumPlanes = true;
  15869. _this.getScene().addCamera(_this);
  15870. if (!_this.getScene().activeCamera) {
  15871. _this.getScene().activeCamera = _this;
  15872. }
  15873. _this.position = position;
  15874. return _this;
  15875. }
  15876. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15877. get: function () {
  15878. return Camera._PERSPECTIVE_CAMERA;
  15879. },
  15880. enumerable: true,
  15881. configurable: true
  15882. });
  15883. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15884. get: function () {
  15885. return Camera._ORTHOGRAPHIC_CAMERA;
  15886. },
  15887. enumerable: true,
  15888. configurable: true
  15889. });
  15890. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15891. get: function () {
  15892. return Camera._FOVMODE_VERTICAL_FIXED;
  15893. },
  15894. enumerable: true,
  15895. configurable: true
  15896. });
  15897. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15898. get: function () {
  15899. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15900. },
  15901. enumerable: true,
  15902. configurable: true
  15903. });
  15904. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15905. get: function () {
  15906. return Camera._RIG_MODE_NONE;
  15907. },
  15908. enumerable: true,
  15909. configurable: true
  15910. });
  15911. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15912. get: function () {
  15913. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15914. },
  15915. enumerable: true,
  15916. configurable: true
  15917. });
  15918. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15919. get: function () {
  15920. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15926. get: function () {
  15927. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15933. get: function () {
  15934. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15935. },
  15936. enumerable: true,
  15937. configurable: true
  15938. });
  15939. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15940. get: function () {
  15941. return Camera._RIG_MODE_VR;
  15942. },
  15943. enumerable: true,
  15944. configurable: true
  15945. });
  15946. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15947. get: function () {
  15948. return Camera._RIG_MODE_WEBVR;
  15949. },
  15950. enumerable: true,
  15951. configurable: true
  15952. });
  15953. /**
  15954. * Store current camera state (fov, position, etc..)
  15955. */
  15956. Camera.prototype.storeState = function () {
  15957. this._stateStored = true;
  15958. this._storedFov = this.fov;
  15959. return this;
  15960. };
  15961. /**
  15962. * Restores the camera state values if it has been stored. You must call storeState() first
  15963. */
  15964. Camera.prototype._restoreStateValues = function () {
  15965. if (!this._stateStored) {
  15966. return false;
  15967. }
  15968. this.fov = this._storedFov;
  15969. return true;
  15970. };
  15971. /**
  15972. * Restored camera state. You must call storeState() first
  15973. */
  15974. Camera.prototype.restoreState = function () {
  15975. if (this._restoreStateValues()) {
  15976. this.onRestoreStateObservable.notifyObservers(this);
  15977. return true;
  15978. }
  15979. return false;
  15980. };
  15981. Camera.prototype.getClassName = function () {
  15982. return "Camera";
  15983. };
  15984. /**
  15985. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15986. */
  15987. Camera.prototype.toString = function (fullDetails) {
  15988. var ret = "Name: " + this.name;
  15989. ret += ", type: " + this.getClassName();
  15990. if (this.animations) {
  15991. for (var i = 0; i < this.animations.length; i++) {
  15992. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15993. }
  15994. }
  15995. if (fullDetails) {
  15996. }
  15997. return ret;
  15998. };
  15999. Object.defineProperty(Camera.prototype, "globalPosition", {
  16000. get: function () {
  16001. return this._globalPosition;
  16002. },
  16003. enumerable: true,
  16004. configurable: true
  16005. });
  16006. Camera.prototype.getActiveMeshes = function () {
  16007. return this._activeMeshes;
  16008. };
  16009. Camera.prototype.isActiveMesh = function (mesh) {
  16010. return (this._activeMeshes.indexOf(mesh) !== -1);
  16011. };
  16012. //Cache
  16013. Camera.prototype._initCache = function () {
  16014. _super.prototype._initCache.call(this);
  16015. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16016. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16017. this._cache.mode = undefined;
  16018. this._cache.minZ = undefined;
  16019. this._cache.maxZ = undefined;
  16020. this._cache.fov = undefined;
  16021. this._cache.fovMode = undefined;
  16022. this._cache.aspectRatio = undefined;
  16023. this._cache.orthoLeft = undefined;
  16024. this._cache.orthoRight = undefined;
  16025. this._cache.orthoBottom = undefined;
  16026. this._cache.orthoTop = undefined;
  16027. this._cache.renderWidth = undefined;
  16028. this._cache.renderHeight = undefined;
  16029. };
  16030. Camera.prototype._updateCache = function (ignoreParentClass) {
  16031. if (!ignoreParentClass) {
  16032. _super.prototype._updateCache.call(this);
  16033. }
  16034. this._cache.position.copyFrom(this.position);
  16035. this._cache.upVector.copyFrom(this.upVector);
  16036. };
  16037. // Synchronized
  16038. Camera.prototype._isSynchronized = function () {
  16039. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16040. };
  16041. Camera.prototype._isSynchronizedViewMatrix = function () {
  16042. if (!_super.prototype._isSynchronized.call(this))
  16043. return false;
  16044. return this._cache.position.equals(this.position)
  16045. && this._cache.upVector.equals(this.upVector)
  16046. && this.isSynchronizedWithParent();
  16047. };
  16048. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16049. var check = this._cache.mode === this.mode
  16050. && this._cache.minZ === this.minZ
  16051. && this._cache.maxZ === this.maxZ;
  16052. if (!check) {
  16053. return false;
  16054. }
  16055. var engine = this.getEngine();
  16056. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16057. check = this._cache.fov === this.fov
  16058. && this._cache.fovMode === this.fovMode
  16059. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16060. }
  16061. else {
  16062. check = this._cache.orthoLeft === this.orthoLeft
  16063. && this._cache.orthoRight === this.orthoRight
  16064. && this._cache.orthoBottom === this.orthoBottom
  16065. && this._cache.orthoTop === this.orthoTop
  16066. && this._cache.renderWidth === engine.getRenderWidth()
  16067. && this._cache.renderHeight === engine.getRenderHeight();
  16068. }
  16069. return check;
  16070. };
  16071. // Controls
  16072. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16073. };
  16074. Camera.prototype.detachControl = function (element) {
  16075. };
  16076. Camera.prototype.update = function () {
  16077. this._checkInputs();
  16078. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16079. this._updateRigCameras();
  16080. }
  16081. };
  16082. Camera.prototype._checkInputs = function () {
  16083. this.onAfterCheckInputsObservable.notifyObservers(this);
  16084. };
  16085. Object.defineProperty(Camera.prototype, "rigCameras", {
  16086. get: function () {
  16087. return this._rigCameras;
  16088. },
  16089. enumerable: true,
  16090. configurable: true
  16091. });
  16092. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16093. get: function () {
  16094. return this._rigPostProcess;
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16100. // invalidate framebuffer
  16101. if (this._postProcesses.length > 0) {
  16102. this._postProcesses[0].markTextureDirty();
  16103. }
  16104. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16105. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16106. var cam = this._rigCameras[i];
  16107. var rigPostProcess = cam._rigPostProcess;
  16108. // for VR rig, there does not have to be a post process
  16109. if (rigPostProcess) {
  16110. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16111. if (isPass) {
  16112. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16113. cam.isIntermediate = this._postProcesses.length === 0;
  16114. }
  16115. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16116. rigPostProcess.markTextureDirty();
  16117. }
  16118. else {
  16119. cam._postProcesses = this._postProcesses.slice(0);
  16120. }
  16121. }
  16122. };
  16123. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16124. if (insertAt === void 0) { insertAt = null; }
  16125. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16126. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16127. return 0;
  16128. }
  16129. if (insertAt == null || insertAt < 0) {
  16130. this._postProcesses.push(postProcess);
  16131. }
  16132. else {
  16133. this._postProcesses.splice(insertAt, 0, postProcess);
  16134. }
  16135. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16136. return this._postProcesses.indexOf(postProcess);
  16137. };
  16138. Camera.prototype.detachPostProcess = function (postProcess) {
  16139. var idx = this._postProcesses.indexOf(postProcess);
  16140. if (idx !== -1) {
  16141. this._postProcesses.splice(idx, 1);
  16142. }
  16143. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16144. };
  16145. Camera.prototype.getWorldMatrix = function () {
  16146. if (!this._worldMatrix) {
  16147. this._worldMatrix = BABYLON.Matrix.Identity();
  16148. }
  16149. var viewMatrix = this.getViewMatrix();
  16150. viewMatrix.invertToRef(this._worldMatrix);
  16151. return this._worldMatrix;
  16152. };
  16153. Camera.prototype._getViewMatrix = function () {
  16154. return BABYLON.Matrix.Identity();
  16155. };
  16156. Camera.prototype.getViewMatrix = function (force) {
  16157. if (!force && this._isSynchronizedViewMatrix()) {
  16158. return this._computedViewMatrix;
  16159. }
  16160. this.updateCache();
  16161. this._computedViewMatrix = this._getViewMatrix();
  16162. this._currentRenderId = this.getScene().getRenderId();
  16163. this._refreshFrustumPlanes = true;
  16164. if (!this.parent || !this.parent.getWorldMatrix) {
  16165. this._globalPosition.copyFrom(this.position);
  16166. }
  16167. else {
  16168. if (!this._worldMatrix) {
  16169. this._worldMatrix = BABYLON.Matrix.Identity();
  16170. }
  16171. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16172. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16173. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16174. this._computedViewMatrix.invert();
  16175. this._markSyncedWithParent();
  16176. }
  16177. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16178. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16179. }
  16180. this.onViewMatrixChangedObservable.notifyObservers(this);
  16181. return this._computedViewMatrix;
  16182. };
  16183. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16184. this._doNotComputeProjectionMatrix = true;
  16185. if (projection !== undefined) {
  16186. this._projectionMatrix = projection;
  16187. }
  16188. };
  16189. ;
  16190. Camera.prototype.unfreezeProjectionMatrix = function () {
  16191. this._doNotComputeProjectionMatrix = false;
  16192. };
  16193. ;
  16194. Camera.prototype.getProjectionMatrix = function (force) {
  16195. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16196. return this._projectionMatrix;
  16197. }
  16198. // Cache
  16199. this._cache.mode = this.mode;
  16200. this._cache.minZ = this.minZ;
  16201. this._cache.maxZ = this.maxZ;
  16202. // Matrix
  16203. this._refreshFrustumPlanes = true;
  16204. var engine = this.getEngine();
  16205. var scene = this.getScene();
  16206. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16207. this._cache.fov = this.fov;
  16208. this._cache.fovMode = this.fovMode;
  16209. this._cache.aspectRatio = engine.getAspectRatio(this);
  16210. if (this.minZ <= 0) {
  16211. this.minZ = 0.1;
  16212. }
  16213. if (scene.useRightHandedSystem) {
  16214. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16215. }
  16216. else {
  16217. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16218. }
  16219. }
  16220. else {
  16221. var halfWidth = engine.getRenderWidth() / 2.0;
  16222. var halfHeight = engine.getRenderHeight() / 2.0;
  16223. if (scene.useRightHandedSystem) {
  16224. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16225. }
  16226. else {
  16227. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16228. }
  16229. this._cache.orthoLeft = this.orthoLeft;
  16230. this._cache.orthoRight = this.orthoRight;
  16231. this._cache.orthoBottom = this.orthoBottom;
  16232. this._cache.orthoTop = this.orthoTop;
  16233. this._cache.renderWidth = engine.getRenderWidth();
  16234. this._cache.renderHeight = engine.getRenderHeight();
  16235. }
  16236. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16237. return this._projectionMatrix;
  16238. };
  16239. Camera.prototype.getTranformationMatrix = function () {
  16240. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16241. return this._transformMatrix;
  16242. };
  16243. Camera.prototype.updateFrustumPlanes = function () {
  16244. if (!this._refreshFrustumPlanes) {
  16245. return;
  16246. }
  16247. this.getTranformationMatrix();
  16248. if (!this._frustumPlanes) {
  16249. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16250. }
  16251. else {
  16252. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16253. }
  16254. this._refreshFrustumPlanes = false;
  16255. };
  16256. Camera.prototype.isInFrustum = function (target) {
  16257. this.updateFrustumPlanes();
  16258. return target.isInFrustum(this._frustumPlanes);
  16259. };
  16260. Camera.prototype.isCompletelyInFrustum = function (target) {
  16261. this.updateFrustumPlanes();
  16262. return target.isCompletelyInFrustum(this._frustumPlanes);
  16263. };
  16264. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16265. if (length === void 0) { length = 100; }
  16266. if (!transform) {
  16267. transform = this.getWorldMatrix();
  16268. }
  16269. if (!origin) {
  16270. origin = this.position;
  16271. }
  16272. var forward = new BABYLON.Vector3(0, 0, 1);
  16273. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16274. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16275. return new BABYLON.Ray(origin, direction, length);
  16276. };
  16277. Camera.prototype.dispose = function () {
  16278. // Observables
  16279. this.onViewMatrixChangedObservable.clear();
  16280. this.onProjectionMatrixChangedObservable.clear();
  16281. this.onAfterCheckInputsObservable.clear();
  16282. this.onRestoreStateObservable.clear();
  16283. // Inputs
  16284. if (this.inputs) {
  16285. this.inputs.clear();
  16286. }
  16287. // Animations
  16288. this.getScene().stopAnimation(this);
  16289. // Remove from scene
  16290. this.getScene().removeCamera(this);
  16291. while (this._rigCameras.length > 0) {
  16292. var camera = this._rigCameras.pop();
  16293. if (camera) {
  16294. camera.dispose();
  16295. }
  16296. }
  16297. // Postprocesses
  16298. if (this._rigPostProcess) {
  16299. this._rigPostProcess.dispose(this);
  16300. this._rigPostProcess = null;
  16301. this._postProcesses = [];
  16302. }
  16303. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16304. this._rigPostProcess = null;
  16305. this._postProcesses = [];
  16306. }
  16307. else {
  16308. var i = this._postProcesses.length;
  16309. while (--i >= 0) {
  16310. this._postProcesses[i].dispose(this);
  16311. }
  16312. }
  16313. // Render targets
  16314. var i = this.customRenderTargets.length;
  16315. while (--i >= 0) {
  16316. this.customRenderTargets[i].dispose();
  16317. }
  16318. this.customRenderTargets = [];
  16319. // Active Meshes
  16320. this._activeMeshes.dispose();
  16321. _super.prototype.dispose.call(this);
  16322. };
  16323. Object.defineProperty(Camera.prototype, "leftCamera", {
  16324. // ---- Camera rigs section ----
  16325. get: function () {
  16326. if (this._rigCameras.length < 1) {
  16327. return null;
  16328. }
  16329. return this._rigCameras[0];
  16330. },
  16331. enumerable: true,
  16332. configurable: true
  16333. });
  16334. Object.defineProperty(Camera.prototype, "rightCamera", {
  16335. get: function () {
  16336. if (this._rigCameras.length < 2) {
  16337. return null;
  16338. }
  16339. return this._rigCameras[1];
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. Camera.prototype.getLeftTarget = function () {
  16345. if (this._rigCameras.length < 1) {
  16346. return null;
  16347. }
  16348. return this._rigCameras[0].getTarget();
  16349. };
  16350. Camera.prototype.getRightTarget = function () {
  16351. if (this._rigCameras.length < 2) {
  16352. return null;
  16353. }
  16354. return this._rigCameras[1].getTarget();
  16355. };
  16356. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16357. if (this.cameraRigMode === mode) {
  16358. return;
  16359. }
  16360. while (this._rigCameras.length > 0) {
  16361. var camera = this._rigCameras.pop();
  16362. if (camera) {
  16363. camera.dispose();
  16364. }
  16365. }
  16366. this.cameraRigMode = mode;
  16367. this._cameraRigParams = {};
  16368. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16369. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16370. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16371. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16372. // create the rig cameras, unless none
  16373. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16374. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16375. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16376. if (leftCamera && rightCamera) {
  16377. this._rigCameras.push(leftCamera);
  16378. this._rigCameras.push(rightCamera);
  16379. }
  16380. }
  16381. switch (this.cameraRigMode) {
  16382. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16383. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16384. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16385. break;
  16386. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16387. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16388. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16389. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16390. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16391. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16392. break;
  16393. case Camera.RIG_MODE_VR:
  16394. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16395. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16396. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16397. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16398. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16399. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16400. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16401. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16402. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16403. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16404. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16405. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16406. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16407. if (metrics.compensateDistortion) {
  16408. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16409. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16410. }
  16411. break;
  16412. case Camera.RIG_MODE_WEBVR:
  16413. if (rigParams.vrDisplay) {
  16414. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16415. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16416. //Left eye
  16417. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16418. this._rigCameras[0].setCameraRigParameter("left", true);
  16419. //leaving this for future reference
  16420. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16421. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16422. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16423. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16424. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16425. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16426. this._rigCameras[0].parent = this;
  16427. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16428. //Right eye
  16429. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16430. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16431. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16432. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16433. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16434. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16435. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16436. this._rigCameras[1].parent = this;
  16437. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16438. if (Camera.UseAlternateWebVRRendering) {
  16439. this._rigCameras[1]._skipRendering = true;
  16440. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16441. }
  16442. }
  16443. break;
  16444. }
  16445. this._cascadePostProcessesToRigCams();
  16446. this.update();
  16447. };
  16448. Camera.prototype._getVRProjectionMatrix = function () {
  16449. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16450. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16451. return this._projectionMatrix;
  16452. };
  16453. Camera.prototype._updateCameraRotationMatrix = function () {
  16454. //Here for WebVR
  16455. };
  16456. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16457. //Here for WebVR
  16458. };
  16459. /**
  16460. * This function MUST be overwritten by the different WebVR cameras available.
  16461. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16462. */
  16463. Camera.prototype._getWebVRProjectionMatrix = function () {
  16464. return BABYLON.Matrix.Identity();
  16465. };
  16466. /**
  16467. * This function MUST be overwritten by the different WebVR cameras available.
  16468. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16469. */
  16470. Camera.prototype._getWebVRViewMatrix = function () {
  16471. return BABYLON.Matrix.Identity();
  16472. };
  16473. Camera.prototype.setCameraRigParameter = function (name, value) {
  16474. if (!this._cameraRigParams) {
  16475. this._cameraRigParams = {};
  16476. }
  16477. this._cameraRigParams[name] = value;
  16478. //provisionnally:
  16479. if (name === "interaxialDistance") {
  16480. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16481. }
  16482. };
  16483. /**
  16484. * needs to be overridden by children so sub has required properties to be copied
  16485. */
  16486. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16487. return null;
  16488. };
  16489. /**
  16490. * May need to be overridden by children
  16491. */
  16492. Camera.prototype._updateRigCameras = function () {
  16493. for (var i = 0; i < this._rigCameras.length; i++) {
  16494. this._rigCameras[i].minZ = this.minZ;
  16495. this._rigCameras[i].maxZ = this.maxZ;
  16496. this._rigCameras[i].fov = this.fov;
  16497. }
  16498. // only update viewport when ANAGLYPH
  16499. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16500. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16501. }
  16502. };
  16503. Camera.prototype._setupInputs = function () {
  16504. };
  16505. Camera.prototype.serialize = function () {
  16506. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16507. // Type
  16508. serializationObject.type = this.getClassName();
  16509. // Parent
  16510. if (this.parent) {
  16511. serializationObject.parentId = this.parent.id;
  16512. }
  16513. if (this.inputs) {
  16514. this.inputs.serialize(serializationObject);
  16515. }
  16516. // Animations
  16517. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16518. serializationObject.ranges = this.serializeAnimationRanges();
  16519. return serializationObject;
  16520. };
  16521. Camera.prototype.clone = function (name) {
  16522. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16523. };
  16524. Camera.prototype.getDirection = function (localAxis) {
  16525. var result = BABYLON.Vector3.Zero();
  16526. this.getDirectionToRef(localAxis, result);
  16527. return result;
  16528. };
  16529. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16530. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16531. };
  16532. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16533. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16534. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16535. switch (type) {
  16536. case "ArcRotateCamera":
  16537. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16538. case "DeviceOrientationCamera":
  16539. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16540. case "FollowCamera":
  16541. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16542. case "ArcFollowCamera":
  16543. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16544. case "GamepadCamera":
  16545. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16546. case "TouchCamera":
  16547. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16548. case "VirtualJoysticksCamera":
  16549. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16550. case "WebVRFreeCamera":
  16551. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16552. case "WebVRGamepadCamera":
  16553. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16554. case "VRDeviceOrientationFreeCamera":
  16555. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16556. case "VRDeviceOrientationGamepadCamera":
  16557. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16558. case "AnaglyphArcRotateCamera":
  16559. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16560. case "AnaglyphFreeCamera":
  16561. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16562. case "AnaglyphGamepadCamera":
  16563. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16564. case "AnaglyphUniversalCamera":
  16565. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16566. case "StereoscopicArcRotateCamera":
  16567. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16568. case "StereoscopicFreeCamera":
  16569. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16570. case "StereoscopicGamepadCamera":
  16571. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16572. case "StereoscopicUniversalCamera":
  16573. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16574. case "FreeCamera":// Forcing Universal here
  16575. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16576. default:// Universal Camera is the default value
  16577. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16578. }
  16579. };
  16580. Camera.Parse = function (parsedCamera, scene) {
  16581. var type = parsedCamera.type;
  16582. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16583. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16584. // Parent
  16585. if (parsedCamera.parentId) {
  16586. camera._waitingParentId = parsedCamera.parentId;
  16587. }
  16588. //If camera has an input manager, let it parse inputs settings
  16589. if (camera.inputs) {
  16590. camera.inputs.parse(parsedCamera);
  16591. camera._setupInputs();
  16592. }
  16593. if (camera.setPosition) {
  16594. camera.position.copyFromFloats(0, 0, 0);
  16595. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16596. }
  16597. // Target
  16598. if (parsedCamera.target) {
  16599. if (camera.setTarget) {
  16600. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16601. }
  16602. }
  16603. // Apply 3d rig, when found
  16604. if (parsedCamera.cameraRigMode) {
  16605. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16606. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16607. }
  16608. // Animations
  16609. if (parsedCamera.animations) {
  16610. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16611. var parsedAnimation = parsedCamera.animations[animationIndex];
  16612. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16613. }
  16614. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16615. }
  16616. if (parsedCamera.autoAnimate) {
  16617. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16618. }
  16619. return camera;
  16620. };
  16621. // Statics
  16622. Camera._PERSPECTIVE_CAMERA = 0;
  16623. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16624. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16625. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16626. Camera._RIG_MODE_NONE = 0;
  16627. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16628. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16629. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16630. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16631. Camera._RIG_MODE_VR = 20;
  16632. Camera._RIG_MODE_WEBVR = 21;
  16633. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16634. Camera.UseAlternateWebVRRendering = false;
  16635. __decorate([
  16636. BABYLON.serializeAsVector3()
  16637. ], Camera.prototype, "position", void 0);
  16638. __decorate([
  16639. BABYLON.serializeAsVector3()
  16640. ], Camera.prototype, "upVector", void 0);
  16641. __decorate([
  16642. BABYLON.serialize()
  16643. ], Camera.prototype, "orthoLeft", void 0);
  16644. __decorate([
  16645. BABYLON.serialize()
  16646. ], Camera.prototype, "orthoRight", void 0);
  16647. __decorate([
  16648. BABYLON.serialize()
  16649. ], Camera.prototype, "orthoBottom", void 0);
  16650. __decorate([
  16651. BABYLON.serialize()
  16652. ], Camera.prototype, "orthoTop", void 0);
  16653. __decorate([
  16654. BABYLON.serialize()
  16655. ], Camera.prototype, "fov", void 0);
  16656. __decorate([
  16657. BABYLON.serialize()
  16658. ], Camera.prototype, "minZ", void 0);
  16659. __decorate([
  16660. BABYLON.serialize()
  16661. ], Camera.prototype, "maxZ", void 0);
  16662. __decorate([
  16663. BABYLON.serialize()
  16664. ], Camera.prototype, "inertia", void 0);
  16665. __decorate([
  16666. BABYLON.serialize()
  16667. ], Camera.prototype, "mode", void 0);
  16668. __decorate([
  16669. BABYLON.serialize()
  16670. ], Camera.prototype, "layerMask", void 0);
  16671. __decorate([
  16672. BABYLON.serialize()
  16673. ], Camera.prototype, "fovMode", void 0);
  16674. __decorate([
  16675. BABYLON.serialize()
  16676. ], Camera.prototype, "cameraRigMode", void 0);
  16677. __decorate([
  16678. BABYLON.serialize()
  16679. ], Camera.prototype, "interaxialDistance", void 0);
  16680. __decorate([
  16681. BABYLON.serialize()
  16682. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16683. return Camera;
  16684. }(BABYLON.Node));
  16685. BABYLON.Camera = Camera;
  16686. })(BABYLON || (BABYLON = {}));
  16687. //# sourceMappingURL=babylon.camera.js.map
  16688. var BABYLON;
  16689. (function (BABYLON) {
  16690. var RenderingManager = /** @class */ (function () {
  16691. function RenderingManager(scene) {
  16692. this._renderingGroups = new Array();
  16693. this._autoClearDepthStencil = {};
  16694. this._customOpaqueSortCompareFn = {};
  16695. this._customAlphaTestSortCompareFn = {};
  16696. this._customTransparentSortCompareFn = {};
  16697. this._renderinGroupInfo = null;
  16698. this._scene = scene;
  16699. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16700. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16701. }
  16702. }
  16703. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16704. if (depth === void 0) { depth = true; }
  16705. if (stencil === void 0) { stencil = true; }
  16706. if (this._depthStencilBufferAlreadyCleaned) {
  16707. return;
  16708. }
  16709. this._scene.getEngine().clear(null, false, depth, stencil);
  16710. this._depthStencilBufferAlreadyCleaned = true;
  16711. };
  16712. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16713. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16714. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16715. var info = null;
  16716. if (observable) {
  16717. if (!this._renderinGroupInfo) {
  16718. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16719. }
  16720. info = this._renderinGroupInfo;
  16721. info.scene = this._scene;
  16722. info.camera = this._scene.activeCamera;
  16723. }
  16724. // Dispatch sprites
  16725. if (renderSprites) {
  16726. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16727. var manager = this._scene.spriteManagers[index];
  16728. this.dispatchSprites(manager);
  16729. }
  16730. }
  16731. // Render
  16732. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16733. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16734. var renderingGroup = this._renderingGroups[index];
  16735. if (!renderingGroup && !observable)
  16736. continue;
  16737. this._currentIndex = index;
  16738. var renderingGroupMask = 0;
  16739. // Fire PRECLEAR stage
  16740. if (observable && info) {
  16741. renderingGroupMask = Math.pow(2, index);
  16742. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16743. info.renderingGroupId = index;
  16744. observable.notifyObservers(info, renderingGroupMask);
  16745. }
  16746. // Clear depth/stencil if needed
  16747. if (RenderingManager.AUTOCLEAR) {
  16748. var autoClear = this._autoClearDepthStencil[index];
  16749. if (autoClear && autoClear.autoClear) {
  16750. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16751. }
  16752. }
  16753. if (observable && info) {
  16754. // Fire PREOPAQUE stage
  16755. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16756. observable.notifyObservers(info, renderingGroupMask);
  16757. // Fire PRETRANSPARENT stage
  16758. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16759. observable.notifyObservers(info, renderingGroupMask);
  16760. }
  16761. if (renderingGroup)
  16762. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16763. // Fire POSTTRANSPARENT stage
  16764. if (observable && info) {
  16765. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16766. observable.notifyObservers(info, renderingGroupMask);
  16767. }
  16768. }
  16769. };
  16770. RenderingManager.prototype.reset = function () {
  16771. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16772. var renderingGroup = this._renderingGroups[index];
  16773. if (renderingGroup) {
  16774. renderingGroup.prepare();
  16775. }
  16776. }
  16777. };
  16778. RenderingManager.prototype.dispose = function () {
  16779. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16780. var renderingGroup = this._renderingGroups[index];
  16781. if (renderingGroup) {
  16782. renderingGroup.dispose();
  16783. }
  16784. }
  16785. this._renderingGroups.length = 0;
  16786. };
  16787. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16788. if (!this._renderingGroups[renderingGroupId]) {
  16789. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16790. }
  16791. };
  16792. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16793. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16794. this._prepareRenderingGroup(renderingGroupId);
  16795. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16796. };
  16797. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16798. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16799. this._prepareRenderingGroup(renderingGroupId);
  16800. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16801. };
  16802. RenderingManager.prototype.dispatch = function (subMesh) {
  16803. var mesh = subMesh.getMesh();
  16804. var renderingGroupId = mesh.renderingGroupId || 0;
  16805. this._prepareRenderingGroup(renderingGroupId);
  16806. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16807. };
  16808. /**
  16809. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16810. * This allowed control for front to back rendering or reversly depending of the special needs.
  16811. *
  16812. * @param renderingGroupId The rendering group id corresponding to its index
  16813. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16814. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16815. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16816. */
  16817. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16818. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16819. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16820. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16821. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16822. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16823. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16824. if (this._renderingGroups[renderingGroupId]) {
  16825. var group = this._renderingGroups[renderingGroupId];
  16826. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16827. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16828. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16829. }
  16830. };
  16831. /**
  16832. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16833. *
  16834. * @param renderingGroupId The rendering group id corresponding to its index
  16835. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16836. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16837. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16838. */
  16839. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16840. if (depth === void 0) { depth = true; }
  16841. if (stencil === void 0) { stencil = true; }
  16842. this._autoClearDepthStencil[renderingGroupId] = {
  16843. autoClear: autoClearDepthStencil,
  16844. depth: depth,
  16845. stencil: stencil
  16846. };
  16847. };
  16848. /**
  16849. * The max id used for rendering groups (not included)
  16850. */
  16851. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16852. /**
  16853. * The min id used for rendering groups (included)
  16854. */
  16855. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16856. /**
  16857. * Used to globally prevent autoclearing scenes.
  16858. */
  16859. RenderingManager.AUTOCLEAR = true;
  16860. return RenderingManager;
  16861. }());
  16862. BABYLON.RenderingManager = RenderingManager;
  16863. })(BABYLON || (BABYLON = {}));
  16864. //# sourceMappingURL=babylon.renderingManager.js.map
  16865. var BABYLON;
  16866. (function (BABYLON) {
  16867. var RenderingGroup = /** @class */ (function () {
  16868. /**
  16869. * Creates a new rendering group.
  16870. * @param index The rendering group index
  16871. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16872. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16873. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16874. */
  16875. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16876. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16877. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16878. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16879. this.index = index;
  16880. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16881. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16882. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16883. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16884. this._particleSystems = new BABYLON.SmartArray(256);
  16885. this._spriteManagers = new BABYLON.SmartArray(256);
  16886. this._edgesRenderers = new BABYLON.SmartArray(16);
  16887. this._scene = scene;
  16888. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16889. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16890. this.transparentSortCompareFn = transparentSortCompareFn;
  16891. }
  16892. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16893. /**
  16894. * Set the opaque sort comparison function.
  16895. * If null the sub meshes will be render in the order they were created
  16896. */
  16897. set: function (value) {
  16898. this._opaqueSortCompareFn = value;
  16899. if (value) {
  16900. this._renderOpaque = this.renderOpaqueSorted;
  16901. }
  16902. else {
  16903. this._renderOpaque = RenderingGroup.renderUnsorted;
  16904. }
  16905. },
  16906. enumerable: true,
  16907. configurable: true
  16908. });
  16909. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16910. /**
  16911. * Set the alpha test sort comparison function.
  16912. * If null the sub meshes will be render in the order they were created
  16913. */
  16914. set: function (value) {
  16915. this._alphaTestSortCompareFn = value;
  16916. if (value) {
  16917. this._renderAlphaTest = this.renderAlphaTestSorted;
  16918. }
  16919. else {
  16920. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16921. }
  16922. },
  16923. enumerable: true,
  16924. configurable: true
  16925. });
  16926. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16927. /**
  16928. * Set the transparent sort comparison function.
  16929. * If null the sub meshes will be render in the order they were created
  16930. */
  16931. set: function (value) {
  16932. if (value) {
  16933. this._transparentSortCompareFn = value;
  16934. }
  16935. else {
  16936. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16937. }
  16938. this._renderTransparent = this.renderTransparentSorted;
  16939. },
  16940. enumerable: true,
  16941. configurable: true
  16942. });
  16943. /**
  16944. * Render all the sub meshes contained in the group.
  16945. * @param customRenderFunction Used to override the default render behaviour of the group.
  16946. * @returns true if rendered some submeshes.
  16947. */
  16948. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16949. if (customRenderFunction) {
  16950. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16951. return;
  16952. }
  16953. var engine = this._scene.getEngine();
  16954. // Depth only
  16955. if (this._depthOnlySubMeshes.length !== 0) {
  16956. engine.setAlphaTesting(true);
  16957. engine.setColorWrite(false);
  16958. this._renderAlphaTest(this._depthOnlySubMeshes);
  16959. engine.setAlphaTesting(false);
  16960. engine.setColorWrite(true);
  16961. }
  16962. // Opaque
  16963. if (this._opaqueSubMeshes.length !== 0) {
  16964. this._renderOpaque(this._opaqueSubMeshes);
  16965. }
  16966. // Alpha test
  16967. if (this._alphaTestSubMeshes.length !== 0) {
  16968. engine.setAlphaTesting(true);
  16969. this._renderAlphaTest(this._alphaTestSubMeshes);
  16970. engine.setAlphaTesting(false);
  16971. }
  16972. var stencilState = engine.getStencilBuffer();
  16973. engine.setStencilBuffer(false);
  16974. // Sprites
  16975. if (renderSprites) {
  16976. this._renderSprites();
  16977. }
  16978. // Particles
  16979. if (renderParticles) {
  16980. this._renderParticles(activeMeshes);
  16981. }
  16982. if (this.onBeforeTransparentRendering) {
  16983. this.onBeforeTransparentRendering();
  16984. }
  16985. // Transparent
  16986. if (this._transparentSubMeshes.length !== 0) {
  16987. this._renderTransparent(this._transparentSubMeshes);
  16988. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16989. }
  16990. // Set back stencil to false in case it changes before the edge renderer.
  16991. engine.setStencilBuffer(false);
  16992. // Edges
  16993. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16994. this._edgesRenderers.data[edgesRendererIndex].render();
  16995. }
  16996. // Restore Stencil state.
  16997. engine.setStencilBuffer(stencilState);
  16998. };
  16999. /**
  17000. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17001. * @param subMeshes The submeshes to render
  17002. */
  17003. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17004. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17005. };
  17006. /**
  17007. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17008. * @param subMeshes The submeshes to render
  17009. */
  17010. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17011. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17012. };
  17013. /**
  17014. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17015. * @param subMeshes The submeshes to render
  17016. */
  17017. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17018. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17019. };
  17020. /**
  17021. * Renders the submeshes in a specified order.
  17022. * @param subMeshes The submeshes to sort before render
  17023. * @param sortCompareFn The comparison function use to sort
  17024. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17025. * @param transparent Specifies to activate blending if true
  17026. */
  17027. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17028. var subIndex = 0;
  17029. var subMesh;
  17030. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17031. for (; subIndex < subMeshes.length; subIndex++) {
  17032. subMesh = subMeshes.data[subIndex];
  17033. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17034. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17035. }
  17036. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17037. if (sortCompareFn) {
  17038. sortedArray.sort(sortCompareFn);
  17039. }
  17040. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17041. subMesh = sortedArray[subIndex];
  17042. if (transparent) {
  17043. var material = subMesh.getMaterial();
  17044. if (material && material.needDepthPrePass) {
  17045. var engine = material.getScene().getEngine();
  17046. engine.setColorWrite(false);
  17047. engine.setAlphaTesting(true);
  17048. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17049. subMesh.render(false);
  17050. engine.setAlphaTesting(false);
  17051. engine.setColorWrite(true);
  17052. }
  17053. }
  17054. subMesh.render(transparent);
  17055. }
  17056. };
  17057. /**
  17058. * Renders the submeshes in the order they were dispatched (no sort applied).
  17059. * @param subMeshes The submeshes to render
  17060. */
  17061. RenderingGroup.renderUnsorted = function (subMeshes) {
  17062. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17063. var submesh = subMeshes.data[subIndex];
  17064. submesh.render(false);
  17065. }
  17066. };
  17067. /**
  17068. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17069. * are rendered back to front if in the same alpha index.
  17070. *
  17071. * @param a The first submesh
  17072. * @param b The second submesh
  17073. * @returns The result of the comparison
  17074. */
  17075. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17076. // Alpha index first
  17077. if (a._alphaIndex > b._alphaIndex) {
  17078. return 1;
  17079. }
  17080. if (a._alphaIndex < b._alphaIndex) {
  17081. return -1;
  17082. }
  17083. // Then distance to camera
  17084. return RenderingGroup.backToFrontSortCompare(a, b);
  17085. };
  17086. /**
  17087. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17088. * are rendered back to front.
  17089. *
  17090. * @param a The first submesh
  17091. * @param b The second submesh
  17092. * @returns The result of the comparison
  17093. */
  17094. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17095. // Then distance to camera
  17096. if (a._distanceToCamera < b._distanceToCamera) {
  17097. return 1;
  17098. }
  17099. if (a._distanceToCamera > b._distanceToCamera) {
  17100. return -1;
  17101. }
  17102. return 0;
  17103. };
  17104. /**
  17105. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17106. * are rendered front to back (prevent overdraw).
  17107. *
  17108. * @param a The first submesh
  17109. * @param b The second submesh
  17110. * @returns The result of the comparison
  17111. */
  17112. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17113. // Then distance to camera
  17114. if (a._distanceToCamera < b._distanceToCamera) {
  17115. return -1;
  17116. }
  17117. if (a._distanceToCamera > b._distanceToCamera) {
  17118. return 1;
  17119. }
  17120. return 0;
  17121. };
  17122. /**
  17123. * Resets the different lists of submeshes to prepare a new frame.
  17124. */
  17125. RenderingGroup.prototype.prepare = function () {
  17126. this._opaqueSubMeshes.reset();
  17127. this._transparentSubMeshes.reset();
  17128. this._alphaTestSubMeshes.reset();
  17129. this._depthOnlySubMeshes.reset();
  17130. this._particleSystems.reset();
  17131. this._spriteManagers.reset();
  17132. this._edgesRenderers.reset();
  17133. };
  17134. RenderingGroup.prototype.dispose = function () {
  17135. this._opaqueSubMeshes.dispose();
  17136. this._transparentSubMeshes.dispose();
  17137. this._alphaTestSubMeshes.dispose();
  17138. this._depthOnlySubMeshes.dispose();
  17139. this._particleSystems.dispose();
  17140. this._spriteManagers.dispose();
  17141. this._edgesRenderers.dispose();
  17142. };
  17143. /**
  17144. * Inserts the submesh in its correct queue depending on its material.
  17145. * @param subMesh The submesh to dispatch
  17146. */
  17147. RenderingGroup.prototype.dispatch = function (subMesh) {
  17148. var material = subMesh.getMaterial();
  17149. var mesh = subMesh.getMesh();
  17150. if (!material) {
  17151. return;
  17152. }
  17153. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17154. this._transparentSubMeshes.push(subMesh);
  17155. }
  17156. else if (material.needAlphaTesting()) {
  17157. if (material.needDepthPrePass) {
  17158. this._depthOnlySubMeshes.push(subMesh);
  17159. }
  17160. this._alphaTestSubMeshes.push(subMesh);
  17161. }
  17162. else {
  17163. if (material.needDepthPrePass) {
  17164. this._depthOnlySubMeshes.push(subMesh);
  17165. }
  17166. this._opaqueSubMeshes.push(subMesh); // Opaque
  17167. }
  17168. if (mesh._edgesRenderer) {
  17169. this._edgesRenderers.push(mesh._edgesRenderer);
  17170. }
  17171. };
  17172. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17173. this._spriteManagers.push(spriteManager);
  17174. };
  17175. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17176. this._particleSystems.push(particleSystem);
  17177. };
  17178. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17179. if (this._particleSystems.length === 0) {
  17180. return;
  17181. }
  17182. // Particles
  17183. var activeCamera = this._scene.activeCamera;
  17184. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17185. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17186. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17187. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17188. continue;
  17189. }
  17190. var emitter = particleSystem.emitter;
  17191. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17192. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17193. }
  17194. }
  17195. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17196. };
  17197. RenderingGroup.prototype._renderSprites = function () {
  17198. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17199. return;
  17200. }
  17201. // Sprites
  17202. var activeCamera = this._scene.activeCamera;
  17203. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17204. for (var id = 0; id < this._spriteManagers.length; id++) {
  17205. var spriteManager = this._spriteManagers.data[id];
  17206. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17207. spriteManager.render();
  17208. }
  17209. }
  17210. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17211. };
  17212. return RenderingGroup;
  17213. }());
  17214. BABYLON.RenderingGroup = RenderingGroup;
  17215. })(BABYLON || (BABYLON = {}));
  17216. //# sourceMappingURL=babylon.renderingGroup.js.map
  17217. var BABYLON;
  17218. (function (BABYLON) {
  17219. var ClickInfo = /** @class */ (function () {
  17220. function ClickInfo() {
  17221. this._singleClick = false;
  17222. this._doubleClick = false;
  17223. this._hasSwiped = false;
  17224. this._ignore = false;
  17225. }
  17226. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17227. get: function () {
  17228. return this._singleClick;
  17229. },
  17230. set: function (b) {
  17231. this._singleClick = b;
  17232. },
  17233. enumerable: true,
  17234. configurable: true
  17235. });
  17236. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17237. get: function () {
  17238. return this._doubleClick;
  17239. },
  17240. set: function (b) {
  17241. this._doubleClick = b;
  17242. },
  17243. enumerable: true,
  17244. configurable: true
  17245. });
  17246. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17247. get: function () {
  17248. return this._hasSwiped;
  17249. },
  17250. set: function (b) {
  17251. this._hasSwiped = b;
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17257. get: function () {
  17258. return this._ignore;
  17259. },
  17260. set: function (b) {
  17261. this._ignore = b;
  17262. },
  17263. enumerable: true,
  17264. configurable: true
  17265. });
  17266. return ClickInfo;
  17267. }());
  17268. /**
  17269. * This class is used by the onRenderingGroupObservable
  17270. */
  17271. var RenderingGroupInfo = /** @class */ (function () {
  17272. function RenderingGroupInfo() {
  17273. }
  17274. /**
  17275. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17276. * This stage will be fired no matter what
  17277. */
  17278. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17279. /**
  17280. * Called before opaque object are rendered.
  17281. * This stage will be fired only if there's 3D Opaque content to render
  17282. */
  17283. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17284. /**
  17285. * Called after the opaque objects are rendered and before the transparent ones
  17286. * This stage will be fired only if there's 3D transparent content to render
  17287. */
  17288. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17289. /**
  17290. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17291. * This stage will be fired no matter what
  17292. */
  17293. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17294. return RenderingGroupInfo;
  17295. }());
  17296. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17297. /**
  17298. * Represents a scene to be rendered by the engine.
  17299. * @see http://doc.babylonjs.com/page.php?p=21911
  17300. */
  17301. var Scene = /** @class */ (function () {
  17302. /**
  17303. * @constructor
  17304. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17305. */
  17306. function Scene(engine) {
  17307. // Members
  17308. this.autoClear = true;
  17309. this.autoClearDepthAndStencil = true;
  17310. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17311. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17312. this.forceWireframe = false;
  17313. this._forcePointsCloud = false;
  17314. this.forceShowBoundingBoxes = false;
  17315. this.animationsEnabled = true;
  17316. this.constantlyUpdateMeshUnderPointer = false;
  17317. this.hoverCursor = "pointer";
  17318. this.defaultCursor = "";
  17319. /**
  17320. * This is used to call preventDefault() on pointer down
  17321. * in order to block unwanted artifacts like system double clicks
  17322. */
  17323. this.preventDefaultOnPointerDown = true;
  17324. // Metadata
  17325. this.metadata = null;
  17326. /**
  17327. * An event triggered when the scene is disposed.
  17328. * @type {BABYLON.Observable}
  17329. */
  17330. this.onDisposeObservable = new BABYLON.Observable();
  17331. /**
  17332. * An event triggered before rendering the scene (right after animations and physics)
  17333. * @type {BABYLON.Observable}
  17334. */
  17335. this.onBeforeRenderObservable = new BABYLON.Observable();
  17336. /**
  17337. * An event triggered after rendering the scene
  17338. * @type {BABYLON.Observable}
  17339. */
  17340. this.onAfterRenderObservable = new BABYLON.Observable();
  17341. /**
  17342. * An event triggered before animating the scene
  17343. * @type {BABYLON.Observable}
  17344. */
  17345. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17346. /**
  17347. * An event triggered after animations processing
  17348. * @type {BABYLON.Observable}
  17349. */
  17350. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17351. /**
  17352. * An event triggered before draw calls are ready to be sent
  17353. * @type {BABYLON.Observable}
  17354. */
  17355. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17356. /**
  17357. * An event triggered after draw calls have been sent
  17358. * @type {BABYLON.Observable}
  17359. */
  17360. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17361. /**
  17362. * An event triggered when physic simulation is about to be run
  17363. * @type {BABYLON.Observable}
  17364. */
  17365. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17366. /**
  17367. * An event triggered when physic simulation has been done
  17368. * @type {BABYLON.Observable}
  17369. */
  17370. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17371. /**
  17372. * An event triggered when the scene is ready
  17373. * @type {BABYLON.Observable}
  17374. */
  17375. this.onReadyObservable = new BABYLON.Observable();
  17376. /**
  17377. * An event triggered before rendering a camera
  17378. * @type {BABYLON.Observable}
  17379. */
  17380. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17381. /**
  17382. * An event triggered after rendering a camera
  17383. * @type {BABYLON.Observable}
  17384. */
  17385. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17386. /**
  17387. * An event triggered when active meshes evaluation is about to start
  17388. * @type {BABYLON.Observable}
  17389. */
  17390. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17391. /**
  17392. * An event triggered when active meshes evaluation is done
  17393. * @type {BABYLON.Observable}
  17394. */
  17395. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17396. /**
  17397. * An event triggered when particles rendering is about to start
  17398. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17399. * @type {BABYLON.Observable}
  17400. */
  17401. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17402. /**
  17403. * An event triggered when particles rendering is done
  17404. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17405. * @type {BABYLON.Observable}
  17406. */
  17407. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17408. /**
  17409. * An event triggered when sprites rendering is about to start
  17410. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17411. * @type {BABYLON.Observable}
  17412. */
  17413. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17414. /**
  17415. * An event triggered when sprites rendering is done
  17416. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17417. * @type {BABYLON.Observable}
  17418. */
  17419. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17420. /**
  17421. * An event triggered when a camera is created
  17422. * @type {BABYLON.Observable}
  17423. */
  17424. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17425. /**
  17426. * An event triggered when a camera is removed
  17427. * @type {BABYLON.Observable}
  17428. */
  17429. this.onCameraRemovedObservable = new BABYLON.Observable();
  17430. /**
  17431. * An event triggered when a light is created
  17432. * @type {BABYLON.Observable}
  17433. */
  17434. this.onNewLightAddedObservable = new BABYLON.Observable();
  17435. /**
  17436. * An event triggered when a light is removed
  17437. * @type {BABYLON.Observable}
  17438. */
  17439. this.onLightRemovedObservable = new BABYLON.Observable();
  17440. /**
  17441. * An event triggered when a geometry is created
  17442. * @type {BABYLON.Observable}
  17443. */
  17444. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17445. /**
  17446. * An event triggered when a geometry is removed
  17447. * @type {BABYLON.Observable}
  17448. */
  17449. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17450. /**
  17451. * An event triggered when a mesh is created
  17452. * @type {BABYLON.Observable}
  17453. */
  17454. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17455. /**
  17456. * An event triggered when a mesh is removed
  17457. * @type {BABYLON.Observable}
  17458. */
  17459. this.onMeshRemovedObservable = new BABYLON.Observable();
  17460. /**
  17461. * An event triggered when render targets are about to be rendered
  17462. * Can happen multiple times per frame.
  17463. * @type {BABYLON.Observable}
  17464. */
  17465. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17466. /**
  17467. * An event triggered when render targets were rendered.
  17468. * Can happen multiple times per frame.
  17469. * @type {BABYLON.Observable}
  17470. */
  17471. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17472. /**
  17473. * An event triggered before calculating deterministic simulation step
  17474. * @type {BABYLON.Observable}
  17475. */
  17476. this.onBeforeStepObservable = new BABYLON.Observable();
  17477. /**
  17478. * An event triggered after calculating deterministic simulation step
  17479. * @type {BABYLON.Observable}
  17480. */
  17481. this.onAfterStepObservable = new BABYLON.Observable();
  17482. /**
  17483. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17484. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17485. * 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)
  17486. */
  17487. this.onRenderingGroupObservable = new BABYLON.Observable();
  17488. // Animations
  17489. this.animations = [];
  17490. /**
  17491. * 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).
  17492. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17493. */
  17494. this.onPrePointerObservable = new BABYLON.Observable();
  17495. /**
  17496. * Observable event triggered each time an input event is received from the rendering canvas
  17497. */
  17498. this.onPointerObservable = new BABYLON.Observable();
  17499. this._meshPickProceed = false;
  17500. this._previousHasSwiped = false;
  17501. this._currentPickResult = null;
  17502. this._previousPickResult = null;
  17503. this._totalPointersPressed = 0;
  17504. this._doubleClickOccured = false;
  17505. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17506. this.cameraToUseForPointers = null;
  17507. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17508. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17509. this._startingPointerTime = 0;
  17510. this._previousStartingPointerTime = 0;
  17511. // Deterministic lockstep
  17512. this._timeAccumulator = 0;
  17513. this._currentStepId = 0;
  17514. this._currentInternalStep = 0;
  17515. // Keyboard
  17516. /**
  17517. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17518. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17519. */
  17520. this.onPreKeyboardObservable = new BABYLON.Observable();
  17521. /**
  17522. * Observable event triggered each time an keyboard event is received from the hosting window
  17523. */
  17524. this.onKeyboardObservable = new BABYLON.Observable();
  17525. // Coordinate system
  17526. /**
  17527. * use right-handed coordinate system on this scene.
  17528. * @type {boolean}
  17529. */
  17530. this._useRightHandedSystem = false;
  17531. // Fog
  17532. this._fogEnabled = true;
  17533. this._fogMode = Scene.FOGMODE_NONE;
  17534. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17535. this.fogDensity = 0.1;
  17536. this.fogStart = 0;
  17537. this.fogEnd = 1000.0;
  17538. // Lights
  17539. /**
  17540. * is shadow enabled on this scene.
  17541. * @type {boolean}
  17542. */
  17543. this._shadowsEnabled = true;
  17544. /**
  17545. * is light enabled on this scene.
  17546. * @type {boolean}
  17547. */
  17548. this._lightsEnabled = true;
  17549. /**
  17550. * All of the lights added to this scene.
  17551. * @see BABYLON.Light
  17552. * @type {BABYLON.Light[]}
  17553. */
  17554. this.lights = new Array();
  17555. // Cameras
  17556. /** All of the cameras added to this scene. */
  17557. this.cameras = new Array();
  17558. /** All of the active cameras added to this scene. */
  17559. this.activeCameras = new Array();
  17560. // Meshes
  17561. /**
  17562. * All of the (abstract) meshes added to this scene.
  17563. * @see BABYLON.AbstractMesh
  17564. * @type {BABYLON.AbstractMesh[]}
  17565. */
  17566. this.meshes = new Array();
  17567. // Geometries
  17568. this._geometries = new Array();
  17569. this.materials = new Array();
  17570. this.multiMaterials = new Array();
  17571. // Textures
  17572. this._texturesEnabled = true;
  17573. this.textures = new Array();
  17574. // Particles
  17575. this.particlesEnabled = true;
  17576. this.particleSystems = new Array();
  17577. // Sprites
  17578. this.spritesEnabled = true;
  17579. this.spriteManagers = new Array();
  17580. // Layers
  17581. this.layers = new Array();
  17582. this.highlightLayers = new Array();
  17583. // Skeletons
  17584. this._skeletonsEnabled = true;
  17585. this.skeletons = new Array();
  17586. // Morph targets
  17587. this.morphTargetManagers = new Array();
  17588. // Lens flares
  17589. this.lensFlaresEnabled = true;
  17590. this.lensFlareSystems = new Array();
  17591. // Collisions
  17592. this.collisionsEnabled = true;
  17593. /** Defines the gravity applied to this scene */
  17594. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17595. // Postprocesses
  17596. this.postProcesses = new Array();
  17597. this.postProcessesEnabled = true;
  17598. // Customs render targets
  17599. this.renderTargetsEnabled = true;
  17600. this.dumpNextRenderTargets = false;
  17601. this.customRenderTargets = new Array();
  17602. // Imported meshes
  17603. this.importedMeshesFiles = new Array();
  17604. // Probes
  17605. this.probesEnabled = true;
  17606. this.reflectionProbes = new Array();
  17607. this._actionManagers = new Array();
  17608. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  17609. // Procedural textures
  17610. this.proceduralTexturesEnabled = true;
  17611. this._proceduralTextures = new Array();
  17612. this.soundTracks = new Array();
  17613. this._audioEnabled = true;
  17614. this._headphone = false;
  17615. // Performance counters
  17616. this._totalVertices = new BABYLON.PerfCounter();
  17617. this._activeIndices = new BABYLON.PerfCounter();
  17618. this._activeParticles = new BABYLON.PerfCounter();
  17619. this._activeBones = new BABYLON.PerfCounter();
  17620. this._animationTime = 0;
  17621. this.animationTimeScale = 1;
  17622. this._renderId = 0;
  17623. this._executeWhenReadyTimeoutId = -1;
  17624. this._intermediateRendering = false;
  17625. this._viewUpdateFlag = -1;
  17626. this._projectionUpdateFlag = -1;
  17627. this._alternateViewUpdateFlag = -1;
  17628. this._alternateProjectionUpdateFlag = -1;
  17629. this._toBeDisposed = new BABYLON.SmartArray(256);
  17630. this._pendingData = new Array();
  17631. this._isDisposed = false;
  17632. this._activeMeshes = new BABYLON.SmartArray(256);
  17633. this._processedMaterials = new BABYLON.SmartArray(256);
  17634. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  17635. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17636. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  17637. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  17638. this._activeAnimatables = new Array();
  17639. this._transformMatrix = BABYLON.Matrix.Zero();
  17640. this._useAlternateCameraConfiguration = false;
  17641. this._alternateRendering = false;
  17642. this.requireLightSorting = false;
  17643. this._activeMeshesFrozen = false;
  17644. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17645. this._engine.scenes.push(this);
  17646. this._uid = null;
  17647. this._renderingManager = new BABYLON.RenderingManager(this);
  17648. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17649. if (BABYLON.OutlineRenderer) {
  17650. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17651. }
  17652. if (BABYLON.Tools.IsWindowObjectExist()) {
  17653. this.attachControl();
  17654. }
  17655. //simplification queue
  17656. if (BABYLON.SimplificationQueue) {
  17657. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17658. }
  17659. //collision coordinator initialization. For now legacy per default.
  17660. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17661. // Uniform Buffer
  17662. this._createUbo();
  17663. // Default Image processing definition.
  17664. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17665. }
  17666. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17667. /** The fog is deactivated */
  17668. get: function () {
  17669. return Scene._FOGMODE_NONE;
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17675. /** The fog density is following an exponential function */
  17676. get: function () {
  17677. return Scene._FOGMODE_EXP;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17683. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17684. get: function () {
  17685. return Scene._FOGMODE_EXP2;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17691. /** The fog density is following a linear function. */
  17692. get: function () {
  17693. return Scene._FOGMODE_LINEAR;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17699. /**
  17700. * Texture used in all pbr material as the reflection texture.
  17701. * As in the majority of the scene they are the same (exception for multi room and so on),
  17702. * this is easier to reference from here than from all the materials.
  17703. */
  17704. get: function () {
  17705. return this._environmentTexture;
  17706. },
  17707. /**
  17708. * Texture used in all pbr material as the reflection texture.
  17709. * As in the majority of the scene they are the same (exception for multi room and so on),
  17710. * this is easier to set here than in all the materials.
  17711. */
  17712. set: function (value) {
  17713. if (this._environmentTexture === value) {
  17714. return;
  17715. }
  17716. this._environmentTexture = value;
  17717. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17723. /**
  17724. * Default image processing configuration used either in the rendering
  17725. * Forward main pass or through the imageProcessingPostProcess if present.
  17726. * As in the majority of the scene they are the same (exception for multi camera),
  17727. * this is easier to reference from here than from all the materials and post process.
  17728. *
  17729. * No setter as we it is a shared configuration, you can set the values instead.
  17730. */
  17731. get: function () {
  17732. return this._imageProcessingConfiguration;
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17738. get: function () {
  17739. return this._forcePointsCloud;
  17740. },
  17741. set: function (value) {
  17742. if (this._forcePointsCloud === value) {
  17743. return;
  17744. }
  17745. this._forcePointsCloud = value;
  17746. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. Object.defineProperty(Scene.prototype, "onDispose", {
  17752. /** A function to be executed when this scene is disposed. */
  17753. set: function (callback) {
  17754. if (this._onDisposeObserver) {
  17755. this.onDisposeObservable.remove(this._onDisposeObserver);
  17756. }
  17757. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(Scene.prototype, "beforeRender", {
  17763. /** A function to be executed before rendering this scene */
  17764. set: function (callback) {
  17765. if (this._onBeforeRenderObserver) {
  17766. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17767. }
  17768. if (callback) {
  17769. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17770. }
  17771. },
  17772. enumerable: true,
  17773. configurable: true
  17774. });
  17775. Object.defineProperty(Scene.prototype, "afterRender", {
  17776. /** A function to be executed after rendering this scene */
  17777. set: function (callback) {
  17778. if (this._onAfterRenderObserver) {
  17779. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17780. }
  17781. if (callback) {
  17782. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17783. }
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17789. set: function (callback) {
  17790. if (this._onBeforeCameraRenderObserver) {
  17791. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17792. }
  17793. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17794. },
  17795. enumerable: true,
  17796. configurable: true
  17797. });
  17798. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17799. set: function (callback) {
  17800. if (this._onAfterCameraRenderObserver) {
  17801. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17802. }
  17803. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17809. get: function () {
  17810. if (!this._gamepadManager) {
  17811. this._gamepadManager = new BABYLON.GamepadManager();
  17812. }
  17813. return this._gamepadManager;
  17814. },
  17815. enumerable: true,
  17816. configurable: true
  17817. });
  17818. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17819. get: function () {
  17820. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17826. get: function () {
  17827. return this._useRightHandedSystem;
  17828. },
  17829. set: function (value) {
  17830. if (this._useRightHandedSystem === value) {
  17831. return;
  17832. }
  17833. this._useRightHandedSystem = value;
  17834. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Scene.prototype.setStepId = function (newStepId) {
  17840. this._currentStepId = newStepId;
  17841. };
  17842. ;
  17843. Scene.prototype.getStepId = function () {
  17844. return this._currentStepId;
  17845. };
  17846. ;
  17847. Scene.prototype.getInternalStep = function () {
  17848. return this._currentInternalStep;
  17849. };
  17850. ;
  17851. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17852. get: function () {
  17853. return this._fogEnabled;
  17854. },
  17855. /**
  17856. * is fog enabled on this scene.
  17857. */
  17858. set: function (value) {
  17859. if (this._fogEnabled === value) {
  17860. return;
  17861. }
  17862. this._fogEnabled = value;
  17863. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17864. },
  17865. enumerable: true,
  17866. configurable: true
  17867. });
  17868. Object.defineProperty(Scene.prototype, "fogMode", {
  17869. get: function () {
  17870. return this._fogMode;
  17871. },
  17872. set: function (value) {
  17873. if (this._fogMode === value) {
  17874. return;
  17875. }
  17876. this._fogMode = value;
  17877. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17878. },
  17879. enumerable: true,
  17880. configurable: true
  17881. });
  17882. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17883. get: function () {
  17884. return this._shadowsEnabled;
  17885. },
  17886. set: function (value) {
  17887. if (this._shadowsEnabled === value) {
  17888. return;
  17889. }
  17890. this._shadowsEnabled = value;
  17891. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17892. },
  17893. enumerable: true,
  17894. configurable: true
  17895. });
  17896. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17897. get: function () {
  17898. return this._lightsEnabled;
  17899. },
  17900. set: function (value) {
  17901. if (this._lightsEnabled === value) {
  17902. return;
  17903. }
  17904. this._lightsEnabled = value;
  17905. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17906. },
  17907. enumerable: true,
  17908. configurable: true
  17909. });
  17910. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17911. /** The default material used on meshes when no material is affected */
  17912. get: function () {
  17913. if (!this._defaultMaterial) {
  17914. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17915. }
  17916. return this._defaultMaterial;
  17917. },
  17918. /** The default material used on meshes when no material is affected */
  17919. set: function (value) {
  17920. this._defaultMaterial = value;
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17926. get: function () {
  17927. return this._texturesEnabled;
  17928. },
  17929. set: function (value) {
  17930. if (this._texturesEnabled === value) {
  17931. return;
  17932. }
  17933. this._texturesEnabled = value;
  17934. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17935. },
  17936. enumerable: true,
  17937. configurable: true
  17938. });
  17939. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17940. get: function () {
  17941. return this._skeletonsEnabled;
  17942. },
  17943. set: function (value) {
  17944. if (this._skeletonsEnabled === value) {
  17945. return;
  17946. }
  17947. this._skeletonsEnabled = value;
  17948. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17954. get: function () {
  17955. if (!this._postProcessRenderPipelineManager) {
  17956. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17957. }
  17958. return this._postProcessRenderPipelineManager;
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17964. get: function () {
  17965. if (!this._mainSoundTrack) {
  17966. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17967. }
  17968. return this._mainSoundTrack;
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17974. get: function () {
  17975. return this._alternateRendering;
  17976. },
  17977. enumerable: true,
  17978. configurable: true
  17979. });
  17980. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17981. get: function () {
  17982. return this._frustumPlanes;
  17983. },
  17984. enumerable: true,
  17985. configurable: true
  17986. });
  17987. Object.defineProperty(Scene.prototype, "debugLayer", {
  17988. // Properties
  17989. get: function () {
  17990. if (!this._debugLayer) {
  17991. this._debugLayer = new BABYLON.DebugLayer(this);
  17992. }
  17993. return this._debugLayer;
  17994. },
  17995. enumerable: true,
  17996. configurable: true
  17997. });
  17998. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17999. get: function () {
  18000. return this._workerCollisions;
  18001. },
  18002. set: function (enabled) {
  18003. if (!BABYLON.CollisionCoordinatorLegacy) {
  18004. return;
  18005. }
  18006. enabled = (enabled && !!Worker);
  18007. this._workerCollisions = enabled;
  18008. if (this.collisionCoordinator) {
  18009. this.collisionCoordinator.destroy();
  18010. }
  18011. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18012. this.collisionCoordinator.init(this);
  18013. },
  18014. enumerable: true,
  18015. configurable: true
  18016. });
  18017. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18018. get: function () {
  18019. return this._selectionOctree;
  18020. },
  18021. enumerable: true,
  18022. configurable: true
  18023. });
  18024. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18025. /**
  18026. * The mesh that is currently under the pointer.
  18027. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18028. */
  18029. get: function () {
  18030. return this._pointerOverMesh;
  18031. },
  18032. enumerable: true,
  18033. configurable: true
  18034. });
  18035. Object.defineProperty(Scene.prototype, "pointerX", {
  18036. /**
  18037. * Current on-screen X position of the pointer
  18038. * @return {number} X position of the pointer
  18039. */
  18040. get: function () {
  18041. return this._pointerX;
  18042. },
  18043. enumerable: true,
  18044. configurable: true
  18045. });
  18046. Object.defineProperty(Scene.prototype, "pointerY", {
  18047. /**
  18048. * Current on-screen Y position of the pointer
  18049. * @return {number} Y position of the pointer
  18050. */
  18051. get: function () {
  18052. return this._pointerY;
  18053. },
  18054. enumerable: true,
  18055. configurable: true
  18056. });
  18057. Scene.prototype.getCachedMaterial = function () {
  18058. return this._cachedMaterial;
  18059. };
  18060. Scene.prototype.getCachedEffect = function () {
  18061. return this._cachedEffect;
  18062. };
  18063. Scene.prototype.getCachedVisibility = function () {
  18064. return this._cachedVisibility;
  18065. };
  18066. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18067. if (visibility === void 0) { visibility = 1; }
  18068. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18069. };
  18070. Scene.prototype.getBoundingBoxRenderer = function () {
  18071. if (!this._boundingBoxRenderer) {
  18072. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18073. }
  18074. return this._boundingBoxRenderer;
  18075. };
  18076. Scene.prototype.getOutlineRenderer = function () {
  18077. return this._outlineRenderer;
  18078. };
  18079. Scene.prototype.getEngine = function () {
  18080. return this._engine;
  18081. };
  18082. Scene.prototype.getTotalVertices = function () {
  18083. return this._totalVertices.current;
  18084. };
  18085. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18086. get: function () {
  18087. return this._totalVertices;
  18088. },
  18089. enumerable: true,
  18090. configurable: true
  18091. });
  18092. Scene.prototype.getActiveIndices = function () {
  18093. return this._activeIndices.current;
  18094. };
  18095. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18096. get: function () {
  18097. return this._activeIndices;
  18098. },
  18099. enumerable: true,
  18100. configurable: true
  18101. });
  18102. Scene.prototype.getActiveParticles = function () {
  18103. return this._activeParticles.current;
  18104. };
  18105. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18106. get: function () {
  18107. return this._activeParticles;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. Scene.prototype.getActiveBones = function () {
  18113. return this._activeBones.current;
  18114. };
  18115. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18116. get: function () {
  18117. return this._activeBones;
  18118. },
  18119. enumerable: true,
  18120. configurable: true
  18121. });
  18122. // Stats
  18123. Scene.prototype.getInterFramePerfCounter = function () {
  18124. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18125. return 0;
  18126. };
  18127. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18128. get: function () {
  18129. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18130. return null;
  18131. },
  18132. enumerable: true,
  18133. configurable: true
  18134. });
  18135. Scene.prototype.getLastFrameDuration = function () {
  18136. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18137. return 0;
  18138. };
  18139. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18140. get: function () {
  18141. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18142. return null;
  18143. },
  18144. enumerable: true,
  18145. configurable: true
  18146. });
  18147. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18148. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18149. return 0;
  18150. };
  18151. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18152. get: function () {
  18153. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18154. return null;
  18155. },
  18156. enumerable: true,
  18157. configurable: true
  18158. });
  18159. Scene.prototype.getActiveMeshes = function () {
  18160. return this._activeMeshes;
  18161. };
  18162. Scene.prototype.getRenderTargetsDuration = function () {
  18163. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18164. return 0;
  18165. };
  18166. Scene.prototype.getRenderDuration = function () {
  18167. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18168. return 0;
  18169. };
  18170. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18171. get: function () {
  18172. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18173. return null;
  18174. },
  18175. enumerable: true,
  18176. configurable: true
  18177. });
  18178. Scene.prototype.getParticlesDuration = function () {
  18179. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18180. return 0;
  18181. };
  18182. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18183. get: function () {
  18184. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18185. return null;
  18186. },
  18187. enumerable: true,
  18188. configurable: true
  18189. });
  18190. Scene.prototype.getSpritesDuration = function () {
  18191. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18192. return 0;
  18193. };
  18194. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18195. get: function () {
  18196. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18197. return null;
  18198. },
  18199. enumerable: true,
  18200. configurable: true
  18201. });
  18202. Scene.prototype.getAnimationRatio = function () {
  18203. return this._animationRatio;
  18204. };
  18205. Scene.prototype.getRenderId = function () {
  18206. return this._renderId;
  18207. };
  18208. Scene.prototype.incrementRenderId = function () {
  18209. this._renderId++;
  18210. };
  18211. Scene.prototype._updatePointerPosition = function (evt) {
  18212. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18213. if (!canvasRect) {
  18214. return;
  18215. }
  18216. this._pointerX = evt.clientX - canvasRect.left;
  18217. this._pointerY = evt.clientY - canvasRect.top;
  18218. this._unTranslatedPointerX = this._pointerX;
  18219. this._unTranslatedPointerY = this._pointerY;
  18220. };
  18221. Scene.prototype._createUbo = function () {
  18222. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18223. this._sceneUbo.addUniform("viewProjection", 16);
  18224. this._sceneUbo.addUniform("view", 16);
  18225. };
  18226. Scene.prototype._createAlternateUbo = function () {
  18227. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18228. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18229. this._alternateSceneUbo.addUniform("view", 16);
  18230. };
  18231. // Pointers handling
  18232. /**
  18233. * Use this method to simulate a pointer move on a mesh
  18234. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18235. */
  18236. Scene.prototype.simulatePointerMove = function (pickResult) {
  18237. var evt = new PointerEvent("pointermove");
  18238. return this._processPointerMove(pickResult, evt);
  18239. };
  18240. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18241. var canvas = this._engine.getRenderingCanvas();
  18242. if (!canvas) {
  18243. return this;
  18244. }
  18245. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18246. this.setPointerOverSprite(null);
  18247. this.setPointerOverMesh(pickResult.pickedMesh);
  18248. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18249. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18250. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18251. }
  18252. else {
  18253. canvas.style.cursor = this.hoverCursor;
  18254. }
  18255. }
  18256. else {
  18257. canvas.style.cursor = this.defaultCursor;
  18258. }
  18259. }
  18260. else {
  18261. this.setPointerOverMesh(null);
  18262. // Sprites
  18263. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18264. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18265. this.setPointerOverSprite(pickResult.pickedSprite);
  18266. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18267. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18268. }
  18269. else {
  18270. canvas.style.cursor = this.hoverCursor;
  18271. }
  18272. }
  18273. else {
  18274. this.setPointerOverSprite(null);
  18275. // Restore pointer
  18276. canvas.style.cursor = this.defaultCursor;
  18277. }
  18278. }
  18279. if (pickResult) {
  18280. if (this.onPointerMove) {
  18281. this.onPointerMove(evt, pickResult);
  18282. }
  18283. if (this.onPointerObservable.hasObservers()) {
  18284. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18285. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18286. this.onPointerObservable.notifyObservers(pi, type);
  18287. }
  18288. }
  18289. return this;
  18290. };
  18291. /**
  18292. * Use this method to simulate a pointer down on a mesh
  18293. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18294. */
  18295. Scene.prototype.simulatePointerDown = function (pickResult) {
  18296. var evt = new PointerEvent("pointerdown");
  18297. return this._processPointerDown(pickResult, evt);
  18298. };
  18299. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18300. var _this = this;
  18301. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18302. this._pickedDownMesh = pickResult.pickedMesh;
  18303. var actionManager = pickResult.pickedMesh.actionManager;
  18304. if (actionManager) {
  18305. if (actionManager.hasPickTriggers) {
  18306. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18307. switch (evt.button) {
  18308. case 0:
  18309. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18310. break;
  18311. case 1:
  18312. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18313. break;
  18314. case 2:
  18315. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18316. break;
  18317. }
  18318. }
  18319. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18320. window.setTimeout(function () {
  18321. 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);
  18322. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18323. if (_this._totalPointersPressed !== 0 &&
  18324. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18325. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18326. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18327. _this._startingPointerTime = 0;
  18328. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18329. }
  18330. }
  18331. }, Scene.LongPressDelay);
  18332. }
  18333. }
  18334. }
  18335. if (pickResult) {
  18336. if (this.onPointerDown) {
  18337. this.onPointerDown(evt, pickResult);
  18338. }
  18339. if (this.onPointerObservable.hasObservers()) {
  18340. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18341. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18342. this.onPointerObservable.notifyObservers(pi, type);
  18343. }
  18344. }
  18345. return this;
  18346. };
  18347. /**
  18348. * Use this method to simulate a pointer up on a mesh
  18349. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18350. */
  18351. Scene.prototype.simulatePointerUp = function (pickResult) {
  18352. var evt = new PointerEvent("pointerup");
  18353. var clickInfo = new ClickInfo();
  18354. clickInfo.singleClick = true;
  18355. return this._processPointerUp(pickResult, evt, clickInfo);
  18356. };
  18357. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18358. if (pickResult && pickResult && pickResult.pickedMesh) {
  18359. this._pickedUpMesh = pickResult.pickedMesh;
  18360. if (this._pickedDownMesh === this._pickedUpMesh) {
  18361. if (this.onPointerPick) {
  18362. this.onPointerPick(evt, pickResult);
  18363. }
  18364. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18365. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18366. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18367. this.onPointerObservable.notifyObservers(pi, type);
  18368. }
  18369. }
  18370. if (pickResult.pickedMesh.actionManager) {
  18371. if (clickInfo.ignore) {
  18372. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18373. }
  18374. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18375. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18376. }
  18377. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18379. }
  18380. }
  18381. }
  18382. if (this._pickedDownMesh &&
  18383. this._pickedDownMesh.actionManager &&
  18384. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18385. this._pickedDownMesh !== this._pickedUpMesh) {
  18386. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18387. }
  18388. if (this.onPointerUp) {
  18389. this.onPointerUp(evt, pickResult);
  18390. }
  18391. if (this.onPointerObservable.hasObservers()) {
  18392. if (!clickInfo.ignore) {
  18393. if (!clickInfo.hasSwiped) {
  18394. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18395. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18396. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18397. this.onPointerObservable.notifyObservers(pi, type);
  18398. }
  18399. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18400. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18401. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18402. this.onPointerObservable.notifyObservers(pi, type);
  18403. }
  18404. }
  18405. }
  18406. else {
  18407. var type = BABYLON.PointerEventTypes.POINTERUP;
  18408. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18409. this.onPointerObservable.notifyObservers(pi, type);
  18410. }
  18411. }
  18412. return this;
  18413. };
  18414. /**
  18415. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18416. * @param attachUp defines if you want to attach events to pointerup
  18417. * @param attachDown defines if you want to attach events to pointerdown
  18418. * @param attachMove defines if you want to attach events to pointermove
  18419. */
  18420. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18421. var _this = this;
  18422. if (attachUp === void 0) { attachUp = true; }
  18423. if (attachDown === void 0) { attachDown = true; }
  18424. if (attachMove === void 0) { attachMove = true; }
  18425. this._initActionManager = function (act, clickInfo) {
  18426. if (!_this._meshPickProceed) {
  18427. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18428. _this._currentPickResult = pickResult;
  18429. if (pickResult) {
  18430. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18431. }
  18432. _this._meshPickProceed = true;
  18433. }
  18434. return act;
  18435. };
  18436. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18437. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18438. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18439. btn !== _this._previousButtonPressed) {
  18440. _this._doubleClickOccured = false;
  18441. clickInfo.singleClick = true;
  18442. clickInfo.ignore = false;
  18443. cb(clickInfo, _this._currentPickResult);
  18444. }
  18445. };
  18446. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18447. var clickInfo = new ClickInfo();
  18448. _this._currentPickResult = null;
  18449. var act = null;
  18450. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18451. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18452. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18453. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18454. act = _this._initActionManager(act, clickInfo);
  18455. if (act)
  18456. checkPicking = act.hasPickTriggers;
  18457. }
  18458. if (checkPicking) {
  18459. var btn = evt.button;
  18460. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18461. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18462. if (!clickInfo.hasSwiped) {
  18463. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18464. if (!checkSingleClickImmediately) {
  18465. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18466. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18467. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18468. act = _this._initActionManager(act, clickInfo);
  18469. if (act)
  18470. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18471. }
  18472. }
  18473. if (checkSingleClickImmediately) {
  18474. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18475. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18476. btn !== _this._previousButtonPressed) {
  18477. clickInfo.singleClick = true;
  18478. cb(clickInfo, _this._currentPickResult);
  18479. }
  18480. }
  18481. else {
  18482. // wait that no double click has been raised during the double click delay
  18483. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18484. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18485. }
  18486. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18487. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18488. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18489. act = _this._initActionManager(act, clickInfo);
  18490. if (act)
  18491. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18492. }
  18493. if (checkDoubleClick) {
  18494. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18495. if (btn === _this._previousButtonPressed &&
  18496. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18497. !_this._doubleClickOccured) {
  18498. // pointer has not moved for 2 clicks, it's a double click
  18499. if (!clickInfo.hasSwiped &&
  18500. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18501. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18502. _this._previousStartingPointerTime = 0;
  18503. _this._doubleClickOccured = true;
  18504. clickInfo.doubleClick = true;
  18505. clickInfo.ignore = false;
  18506. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18507. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18508. }
  18509. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18510. cb(clickInfo, _this._currentPickResult);
  18511. }
  18512. else {
  18513. _this._doubleClickOccured = false;
  18514. _this._previousStartingPointerTime = _this._startingPointerTime;
  18515. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18516. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18517. _this._previousButtonPressed = btn;
  18518. _this._previousHasSwiped = clickInfo.hasSwiped;
  18519. if (Scene.ExclusiveDoubleClickMode) {
  18520. if (_this._previousDelayedSimpleClickTimeout) {
  18521. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18522. }
  18523. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18524. cb(clickInfo, _this._previousPickResult);
  18525. }
  18526. else {
  18527. cb(clickInfo, _this._currentPickResult);
  18528. }
  18529. }
  18530. }
  18531. else {
  18532. _this._doubleClickOccured = false;
  18533. _this._previousStartingPointerTime = _this._startingPointerTime;
  18534. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18535. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18536. _this._previousButtonPressed = btn;
  18537. _this._previousHasSwiped = clickInfo.hasSwiped;
  18538. }
  18539. }
  18540. }
  18541. }
  18542. clickInfo.ignore = true;
  18543. cb(clickInfo, _this._currentPickResult);
  18544. };
  18545. this._spritePredicate = function (sprite) {
  18546. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18547. };
  18548. this._onPointerMove = function (evt) {
  18549. _this._updatePointerPosition(evt);
  18550. // PreObservable support
  18551. if (_this.onPrePointerObservable.hasObservers()) {
  18552. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18553. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18554. _this.onPrePointerObservable.notifyObservers(pi, type);
  18555. if (pi.skipOnPointerObservable) {
  18556. return;
  18557. }
  18558. }
  18559. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18560. return;
  18561. }
  18562. if (!_this.pointerMovePredicate) {
  18563. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18564. }
  18565. // Meshes
  18566. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18567. _this._processPointerMove(pickResult, evt);
  18568. };
  18569. this._onPointerDown = function (evt) {
  18570. _this._totalPointersPressed++;
  18571. _this._pickedDownMesh = null;
  18572. _this._meshPickProceed = false;
  18573. _this._updatePointerPosition(evt);
  18574. if (_this.preventDefaultOnPointerDown && canvas) {
  18575. evt.preventDefault();
  18576. canvas.focus();
  18577. }
  18578. // PreObservable support
  18579. if (_this.onPrePointerObservable.hasObservers()) {
  18580. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18581. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18582. _this.onPrePointerObservable.notifyObservers(pi, type);
  18583. if (pi.skipOnPointerObservable) {
  18584. return;
  18585. }
  18586. }
  18587. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18588. return;
  18589. }
  18590. _this._startingPointerPosition.x = _this._pointerX;
  18591. _this._startingPointerPosition.y = _this._pointerY;
  18592. _this._startingPointerTime = new Date().getTime();
  18593. if (!_this.pointerDownPredicate) {
  18594. _this.pointerDownPredicate = function (mesh) {
  18595. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18596. };
  18597. }
  18598. // Meshes
  18599. _this._pickedDownMesh = null;
  18600. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18601. _this._processPointerDown(pickResult, evt);
  18602. // Sprites
  18603. _this._pickedDownSprite = null;
  18604. if (_this.spriteManagers.length > 0) {
  18605. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18606. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18607. if (pickResult.pickedSprite.actionManager) {
  18608. _this._pickedDownSprite = pickResult.pickedSprite;
  18609. switch (evt.button) {
  18610. case 0:
  18611. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18612. break;
  18613. case 1:
  18614. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18615. break;
  18616. case 2:
  18617. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18618. break;
  18619. }
  18620. if (pickResult.pickedSprite.actionManager) {
  18621. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18622. }
  18623. }
  18624. }
  18625. }
  18626. };
  18627. this._onPointerUp = function (evt) {
  18628. if (_this._totalPointersPressed === 0) {
  18629. return; // So we need to test it the pointer down was pressed before.
  18630. }
  18631. _this._totalPointersPressed--;
  18632. _this._pickedUpMesh = null;
  18633. _this._meshPickProceed = false;
  18634. _this._updatePointerPosition(evt);
  18635. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18636. // PreObservable support
  18637. if (_this.onPrePointerObservable.hasObservers()) {
  18638. if (!clickInfo.ignore) {
  18639. if (!clickInfo.hasSwiped) {
  18640. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18641. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18642. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18643. _this.onPrePointerObservable.notifyObservers(pi, type);
  18644. if (pi.skipOnPointerObservable) {
  18645. return;
  18646. }
  18647. }
  18648. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18649. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18650. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18651. _this.onPrePointerObservable.notifyObservers(pi, type);
  18652. if (pi.skipOnPointerObservable) {
  18653. return;
  18654. }
  18655. }
  18656. }
  18657. }
  18658. else {
  18659. var type = BABYLON.PointerEventTypes.POINTERUP;
  18660. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18661. _this.onPrePointerObservable.notifyObservers(pi, type);
  18662. if (pi.skipOnPointerObservable) {
  18663. return;
  18664. }
  18665. }
  18666. }
  18667. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18668. return;
  18669. }
  18670. if (!_this.pointerUpPredicate) {
  18671. _this.pointerUpPredicate = function (mesh) {
  18672. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18673. };
  18674. }
  18675. // Meshes
  18676. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18677. _this._initActionManager(null, clickInfo);
  18678. }
  18679. if (!pickResult) {
  18680. pickResult = _this._currentPickResult;
  18681. }
  18682. _this._processPointerUp(pickResult, evt, clickInfo);
  18683. // Sprites
  18684. if (_this.spriteManagers.length > 0) {
  18685. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18686. if (spritePickResult) {
  18687. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18688. if (spritePickResult.pickedSprite.actionManager) {
  18689. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18690. if (spritePickResult.pickedSprite.actionManager) {
  18691. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18692. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18693. }
  18694. }
  18695. }
  18696. }
  18697. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18698. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18699. }
  18700. }
  18701. }
  18702. _this._previousPickResult = _this._currentPickResult;
  18703. });
  18704. };
  18705. this._onKeyDown = function (evt) {
  18706. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18707. if (_this.onPreKeyboardObservable.hasObservers()) {
  18708. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18709. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18710. if (pi.skipOnPointerObservable) {
  18711. return;
  18712. }
  18713. }
  18714. if (_this.onKeyboardObservable.hasObservers()) {
  18715. var pi = new BABYLON.KeyboardInfo(type, evt);
  18716. _this.onKeyboardObservable.notifyObservers(pi, type);
  18717. }
  18718. if (_this.actionManager) {
  18719. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18720. }
  18721. };
  18722. this._onKeyUp = function (evt) {
  18723. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18724. if (_this.onPreKeyboardObservable.hasObservers()) {
  18725. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18726. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18727. if (pi.skipOnPointerObservable) {
  18728. return;
  18729. }
  18730. }
  18731. if (_this.onKeyboardObservable.hasObservers()) {
  18732. var pi = new BABYLON.KeyboardInfo(type, evt);
  18733. _this.onKeyboardObservable.notifyObservers(pi, type);
  18734. }
  18735. if (_this.actionManager) {
  18736. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18737. }
  18738. };
  18739. var engine = this.getEngine();
  18740. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18741. if (!canvas) {
  18742. return;
  18743. }
  18744. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18745. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18746. });
  18747. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18748. if (!canvas) {
  18749. return;
  18750. }
  18751. canvas.removeEventListener("keydown", _this._onKeyDown);
  18752. canvas.removeEventListener("keyup", _this._onKeyUp);
  18753. });
  18754. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18755. var canvas = this._engine.getRenderingCanvas();
  18756. if (!canvas) {
  18757. return;
  18758. }
  18759. if (attachMove) {
  18760. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18761. // Wheel
  18762. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18763. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18764. }
  18765. if (attachDown) {
  18766. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18767. }
  18768. if (attachUp) {
  18769. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18770. }
  18771. canvas.tabIndex = 1;
  18772. };
  18773. Scene.prototype.detachControl = function () {
  18774. var engine = this.getEngine();
  18775. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18776. var canvas = engine.getRenderingCanvas();
  18777. if (!canvas) {
  18778. return;
  18779. }
  18780. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18781. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18782. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18783. if (this._onCanvasBlurObserver) {
  18784. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18785. }
  18786. if (this._onCanvasFocusObserver) {
  18787. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18788. }
  18789. // Wheel
  18790. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18791. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18792. // Keyboard
  18793. canvas.removeEventListener("keydown", this._onKeyDown);
  18794. canvas.removeEventListener("keyup", this._onKeyUp);
  18795. // Observables
  18796. this.onKeyboardObservable.clear();
  18797. this.onPreKeyboardObservable.clear();
  18798. this.onPointerObservable.clear();
  18799. this.onPrePointerObservable.clear();
  18800. };
  18801. // Ready
  18802. Scene.prototype.isReady = function () {
  18803. if (this._isDisposed) {
  18804. return false;
  18805. }
  18806. if (this._pendingData.length > 0) {
  18807. return false;
  18808. }
  18809. var index;
  18810. // Geometries
  18811. for (index = 0; index < this._geometries.length; index++) {
  18812. var geometry = this._geometries[index];
  18813. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18814. return false;
  18815. }
  18816. }
  18817. // Meshes
  18818. for (index = 0; index < this.meshes.length; index++) {
  18819. var mesh = this.meshes[index];
  18820. if (!mesh.isEnabled()) {
  18821. continue;
  18822. }
  18823. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18824. continue;
  18825. }
  18826. if (!mesh.isReady()) {
  18827. return false;
  18828. }
  18829. var mat = mesh.material;
  18830. if (mat) {
  18831. if (!mat.isReady(mesh)) {
  18832. return false;
  18833. }
  18834. }
  18835. }
  18836. return true;
  18837. };
  18838. Scene.prototype.resetCachedMaterial = function () {
  18839. this._cachedMaterial = null;
  18840. this._cachedEffect = null;
  18841. this._cachedVisibility = null;
  18842. };
  18843. Scene.prototype.registerBeforeRender = function (func) {
  18844. this.onBeforeRenderObservable.add(func);
  18845. };
  18846. Scene.prototype.unregisterBeforeRender = function (func) {
  18847. this.onBeforeRenderObservable.removeCallback(func);
  18848. };
  18849. Scene.prototype.registerAfterRender = function (func) {
  18850. this.onAfterRenderObservable.add(func);
  18851. };
  18852. Scene.prototype.unregisterAfterRender = function (func) {
  18853. this.onAfterRenderObservable.removeCallback(func);
  18854. };
  18855. Scene.prototype._addPendingData = function (data) {
  18856. this._pendingData.push(data);
  18857. };
  18858. Scene.prototype._removePendingData = function (data) {
  18859. var index = this._pendingData.indexOf(data);
  18860. if (index !== -1) {
  18861. this._pendingData.splice(index, 1);
  18862. }
  18863. };
  18864. Scene.prototype.getWaitingItemsCount = function () {
  18865. return this._pendingData.length;
  18866. };
  18867. /**
  18868. * Registers a function to be executed when the scene is ready.
  18869. * @param {Function} func - the function to be executed.
  18870. */
  18871. Scene.prototype.executeWhenReady = function (func) {
  18872. var _this = this;
  18873. this.onReadyObservable.add(func);
  18874. if (this._executeWhenReadyTimeoutId !== -1) {
  18875. return;
  18876. }
  18877. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18878. _this._checkIsReady();
  18879. }, 150);
  18880. };
  18881. Scene.prototype._checkIsReady = function () {
  18882. var _this = this;
  18883. if (this.isReady()) {
  18884. this.onReadyObservable.notifyObservers(this);
  18885. this.onReadyObservable.clear();
  18886. this._executeWhenReadyTimeoutId = -1;
  18887. return;
  18888. }
  18889. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18890. _this._checkIsReady();
  18891. }, 150);
  18892. };
  18893. // Animations
  18894. /**
  18895. * Will start the animation sequence of a given target
  18896. * @param target - the target
  18897. * @param {number} from - from which frame should animation start
  18898. * @param {number} to - till which frame should animation run.
  18899. * @param {boolean} [loop] - should the animation loop
  18900. * @param {number} [speedRatio] - the speed in which to run the animation
  18901. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18902. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18903. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18904. * See BABYLON.Animatable
  18905. */
  18906. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18907. if (speedRatio === void 0) { speedRatio = 1.0; }
  18908. if (from > to && speedRatio > 0) {
  18909. speedRatio *= -1;
  18910. }
  18911. this.stopAnimation(target);
  18912. if (!animatable) {
  18913. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18914. }
  18915. // Local animations
  18916. if (target.animations) {
  18917. animatable.appendAnimations(target, target.animations);
  18918. }
  18919. // Children animations
  18920. if (target.getAnimatables) {
  18921. var animatables = target.getAnimatables();
  18922. for (var index = 0; index < animatables.length; index++) {
  18923. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18924. }
  18925. }
  18926. animatable.reset();
  18927. return animatable;
  18928. };
  18929. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18930. if (speedRatio === undefined) {
  18931. speedRatio = 1.0;
  18932. }
  18933. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18934. return animatable;
  18935. };
  18936. Scene.prototype.getAnimatableByTarget = function (target) {
  18937. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18938. if (this._activeAnimatables[index].target === target) {
  18939. return this._activeAnimatables[index];
  18940. }
  18941. }
  18942. return null;
  18943. };
  18944. Object.defineProperty(Scene.prototype, "Animatables", {
  18945. get: function () {
  18946. return this._activeAnimatables;
  18947. },
  18948. enumerable: true,
  18949. configurable: true
  18950. });
  18951. /**
  18952. * Will stop the animation of the given target
  18953. * @param target - the target
  18954. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18955. * @see beginAnimation
  18956. */
  18957. Scene.prototype.stopAnimation = function (target, animationName) {
  18958. var animatable = this.getAnimatableByTarget(target);
  18959. if (animatable) {
  18960. animatable.stop(animationName);
  18961. }
  18962. };
  18963. Scene.prototype._animate = function () {
  18964. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18965. return;
  18966. }
  18967. // Getting time
  18968. var now = BABYLON.Tools.Now;
  18969. if (!this._animationTimeLast) {
  18970. if (this._pendingData.length > 0) {
  18971. return;
  18972. }
  18973. this._animationTimeLast = now;
  18974. }
  18975. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18976. this._animationTime += deltaTime;
  18977. this._animationTimeLast = now;
  18978. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18979. this._activeAnimatables[index]._animate(this._animationTime);
  18980. }
  18981. };
  18982. // Matrix
  18983. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18984. this._useAlternateCameraConfiguration = active;
  18985. };
  18986. Scene.prototype.getViewMatrix = function () {
  18987. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18988. };
  18989. Scene.prototype.getProjectionMatrix = function () {
  18990. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18991. };
  18992. Scene.prototype.getTransformMatrix = function () {
  18993. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18994. };
  18995. Scene.prototype.setTransformMatrix = function (view, projection) {
  18996. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18997. return;
  18998. }
  18999. this._viewUpdateFlag = view.updateFlag;
  19000. this._projectionUpdateFlag = projection.updateFlag;
  19001. this._viewMatrix = view;
  19002. this._projectionMatrix = projection;
  19003. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19004. // Update frustum
  19005. if (!this._frustumPlanes) {
  19006. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19007. }
  19008. else {
  19009. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19010. }
  19011. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19012. var otherCamera = this.activeCamera._alternateCamera;
  19013. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19014. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19015. }
  19016. if (this._sceneUbo.useUbo) {
  19017. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19018. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19019. this._sceneUbo.update();
  19020. }
  19021. };
  19022. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19023. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19024. return;
  19025. }
  19026. this._alternateViewUpdateFlag = view.updateFlag;
  19027. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19028. this._alternateViewMatrix = view;
  19029. this._alternateProjectionMatrix = projection;
  19030. if (!this._alternateTransformMatrix) {
  19031. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19032. }
  19033. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19034. if (!this._alternateSceneUbo) {
  19035. this._createAlternateUbo();
  19036. }
  19037. if (this._alternateSceneUbo.useUbo) {
  19038. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19039. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19040. this._alternateSceneUbo.update();
  19041. }
  19042. };
  19043. Scene.prototype.getSceneUniformBuffer = function () {
  19044. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19045. };
  19046. // Methods
  19047. Scene.prototype.getUniqueId = function () {
  19048. var result = Scene._uniqueIdCounter;
  19049. Scene._uniqueIdCounter++;
  19050. return result;
  19051. };
  19052. Scene.prototype.addMesh = function (newMesh) {
  19053. this.meshes.push(newMesh);
  19054. //notify the collision coordinator
  19055. if (this.collisionCoordinator) {
  19056. this.collisionCoordinator.onMeshAdded(newMesh);
  19057. }
  19058. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19059. };
  19060. Scene.prototype.removeMesh = function (toRemove) {
  19061. var index = this.meshes.indexOf(toRemove);
  19062. if (index !== -1) {
  19063. // Remove from the scene if mesh found
  19064. this.meshes.splice(index, 1);
  19065. }
  19066. //notify the collision coordinator
  19067. if (this.collisionCoordinator) {
  19068. this.collisionCoordinator.onMeshRemoved(toRemove);
  19069. }
  19070. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19071. return index;
  19072. };
  19073. Scene.prototype.removeSkeleton = function (toRemove) {
  19074. var index = this.skeletons.indexOf(toRemove);
  19075. if (index !== -1) {
  19076. // Remove from the scene if found
  19077. this.skeletons.splice(index, 1);
  19078. }
  19079. return index;
  19080. };
  19081. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19082. var index = this.morphTargetManagers.indexOf(toRemove);
  19083. if (index !== -1) {
  19084. // Remove from the scene if found
  19085. this.morphTargetManagers.splice(index, 1);
  19086. }
  19087. return index;
  19088. };
  19089. Scene.prototype.removeLight = function (toRemove) {
  19090. var index = this.lights.indexOf(toRemove);
  19091. if (index !== -1) {
  19092. // Remove from the scene if mesh found
  19093. this.lights.splice(index, 1);
  19094. this.sortLightsByPriority();
  19095. }
  19096. this.onLightRemovedObservable.notifyObservers(toRemove);
  19097. return index;
  19098. };
  19099. Scene.prototype.removeCamera = function (toRemove) {
  19100. var index = this.cameras.indexOf(toRemove);
  19101. if (index !== -1) {
  19102. // Remove from the scene if mesh found
  19103. this.cameras.splice(index, 1);
  19104. }
  19105. // Remove from activeCameras
  19106. var index2 = this.activeCameras.indexOf(toRemove);
  19107. if (index2 !== -1) {
  19108. // Remove from the scene if mesh found
  19109. this.activeCameras.splice(index2, 1);
  19110. }
  19111. // Reset the activeCamera
  19112. if (this.activeCamera === toRemove) {
  19113. if (this.cameras.length > 0) {
  19114. this.activeCamera = this.cameras[0];
  19115. }
  19116. else {
  19117. this.activeCamera = null;
  19118. }
  19119. }
  19120. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19121. return index;
  19122. };
  19123. Scene.prototype.addLight = function (newLight) {
  19124. this.lights.push(newLight);
  19125. this.sortLightsByPriority();
  19126. this.onNewLightAddedObservable.notifyObservers(newLight);
  19127. };
  19128. Scene.prototype.sortLightsByPriority = function () {
  19129. if (this.requireLightSorting) {
  19130. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19131. }
  19132. };
  19133. Scene.prototype.addCamera = function (newCamera) {
  19134. this.cameras.push(newCamera);
  19135. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19136. };
  19137. /**
  19138. * Switch active camera
  19139. * @param {Camera} newCamera - new active camera
  19140. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19141. */
  19142. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19143. if (attachControl === void 0) { attachControl = true; }
  19144. var canvas = this._engine.getRenderingCanvas();
  19145. if (!canvas) {
  19146. return;
  19147. }
  19148. if (this.activeCamera) {
  19149. this.activeCamera.detachControl(canvas);
  19150. }
  19151. this.activeCamera = newCamera;
  19152. if (attachControl) {
  19153. newCamera.attachControl(canvas);
  19154. }
  19155. };
  19156. /**
  19157. * sets the active camera of the scene using its ID
  19158. * @param {string} id - the camera's ID
  19159. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19160. * @see activeCamera
  19161. */
  19162. Scene.prototype.setActiveCameraByID = function (id) {
  19163. var camera = this.getCameraByID(id);
  19164. if (camera) {
  19165. this.activeCamera = camera;
  19166. return camera;
  19167. }
  19168. return null;
  19169. };
  19170. /**
  19171. * sets the active camera of the scene using its name
  19172. * @param {string} name - the camera's name
  19173. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19174. * @see activeCamera
  19175. */
  19176. Scene.prototype.setActiveCameraByName = function (name) {
  19177. var camera = this.getCameraByName(name);
  19178. if (camera) {
  19179. this.activeCamera = camera;
  19180. return camera;
  19181. }
  19182. return null;
  19183. };
  19184. /**
  19185. * get a material using its id
  19186. * @param {string} the material's ID
  19187. * @return {BABYLON.Material|null} the material or null if none found.
  19188. */
  19189. Scene.prototype.getMaterialByID = function (id) {
  19190. for (var index = 0; index < this.materials.length; index++) {
  19191. if (this.materials[index].id === id) {
  19192. return this.materials[index];
  19193. }
  19194. }
  19195. return null;
  19196. };
  19197. /**
  19198. * get a material using its name
  19199. * @param {string} the material's name
  19200. * @return {BABYLON.Material|null} the material or null if none found.
  19201. */
  19202. Scene.prototype.getMaterialByName = function (name) {
  19203. for (var index = 0; index < this.materials.length; index++) {
  19204. if (this.materials[index].name === name) {
  19205. return this.materials[index];
  19206. }
  19207. }
  19208. return null;
  19209. };
  19210. Scene.prototype.getLensFlareSystemByName = function (name) {
  19211. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19212. if (this.lensFlareSystems[index].name === name) {
  19213. return this.lensFlareSystems[index];
  19214. }
  19215. }
  19216. return null;
  19217. };
  19218. Scene.prototype.getLensFlareSystemByID = function (id) {
  19219. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19220. if (this.lensFlareSystems[index].id === id) {
  19221. return this.lensFlareSystems[index];
  19222. }
  19223. }
  19224. return null;
  19225. };
  19226. Scene.prototype.getCameraByID = function (id) {
  19227. for (var index = 0; index < this.cameras.length; index++) {
  19228. if (this.cameras[index].id === id) {
  19229. return this.cameras[index];
  19230. }
  19231. }
  19232. return null;
  19233. };
  19234. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19235. for (var index = 0; index < this.cameras.length; index++) {
  19236. if (this.cameras[index].uniqueId === uniqueId) {
  19237. return this.cameras[index];
  19238. }
  19239. }
  19240. return null;
  19241. };
  19242. /**
  19243. * get a camera using its name
  19244. * @param {string} the camera's name
  19245. * @return {BABYLON.Camera|null} the camera or null if none found.
  19246. */
  19247. Scene.prototype.getCameraByName = function (name) {
  19248. for (var index = 0; index < this.cameras.length; index++) {
  19249. if (this.cameras[index].name === name) {
  19250. return this.cameras[index];
  19251. }
  19252. }
  19253. return null;
  19254. };
  19255. /**
  19256. * get a bone using its id
  19257. * @param {string} the bone's id
  19258. * @return {BABYLON.Bone|null} the bone or null if not found
  19259. */
  19260. Scene.prototype.getBoneByID = function (id) {
  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].id === id) {
  19265. return skeleton.bones[boneIndex];
  19266. }
  19267. }
  19268. }
  19269. return null;
  19270. };
  19271. /**
  19272. * get a bone using its id
  19273. * @param {string} the bone's name
  19274. * @return {BABYLON.Bone|null} the bone or null if not found
  19275. */
  19276. Scene.prototype.getBoneByName = function (name) {
  19277. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19278. var skeleton = this.skeletons[skeletonIndex];
  19279. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19280. if (skeleton.bones[boneIndex].name === name) {
  19281. return skeleton.bones[boneIndex];
  19282. }
  19283. }
  19284. }
  19285. return null;
  19286. };
  19287. /**
  19288. * get a light node using its name
  19289. * @param {string} the light's name
  19290. * @return {BABYLON.Light|null} the light or null if none found.
  19291. */
  19292. Scene.prototype.getLightByName = function (name) {
  19293. for (var index = 0; index < this.lights.length; index++) {
  19294. if (this.lights[index].name === name) {
  19295. return this.lights[index];
  19296. }
  19297. }
  19298. return null;
  19299. };
  19300. /**
  19301. * get a light node using its ID
  19302. * @param {string} the light's id
  19303. * @return {BABYLON.Light|null} the light or null if none found.
  19304. */
  19305. Scene.prototype.getLightByID = function (id) {
  19306. for (var index = 0; index < this.lights.length; index++) {
  19307. if (this.lights[index].id === id) {
  19308. return this.lights[index];
  19309. }
  19310. }
  19311. return null;
  19312. };
  19313. /**
  19314. * get a light node using its scene-generated unique ID
  19315. * @param {number} the light's unique id
  19316. * @return {BABYLON.Light|null} the light or null if none found.
  19317. */
  19318. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19319. for (var index = 0; index < this.lights.length; index++) {
  19320. if (this.lights[index].uniqueId === uniqueId) {
  19321. return this.lights[index];
  19322. }
  19323. }
  19324. return null;
  19325. };
  19326. /**
  19327. * get a particle system by id
  19328. * @param id {number} the particle system id
  19329. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19330. */
  19331. Scene.prototype.getParticleSystemByID = function (id) {
  19332. for (var index = 0; index < this.particleSystems.length; index++) {
  19333. if (this.particleSystems[index].id === id) {
  19334. return this.particleSystems[index];
  19335. }
  19336. }
  19337. return null;
  19338. };
  19339. /**
  19340. * get a geometry using its ID
  19341. * @param {string} the geometry's id
  19342. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19343. */
  19344. Scene.prototype.getGeometryByID = function (id) {
  19345. for (var index = 0; index < this._geometries.length; index++) {
  19346. if (this._geometries[index].id === id) {
  19347. return this._geometries[index];
  19348. }
  19349. }
  19350. return null;
  19351. };
  19352. /**
  19353. * add a new geometry to this scene.
  19354. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19355. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19356. * @return {boolean} was the geometry added or not
  19357. */
  19358. Scene.prototype.pushGeometry = function (geometry, force) {
  19359. if (!force && this.getGeometryByID(geometry.id)) {
  19360. return false;
  19361. }
  19362. this._geometries.push(geometry);
  19363. //notify the collision coordinator
  19364. if (this.collisionCoordinator) {
  19365. this.collisionCoordinator.onGeometryAdded(geometry);
  19366. }
  19367. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19368. return true;
  19369. };
  19370. /**
  19371. * Removes an existing geometry
  19372. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19373. * @return {boolean} was the geometry removed or not
  19374. */
  19375. Scene.prototype.removeGeometry = function (geometry) {
  19376. var index = this._geometries.indexOf(geometry);
  19377. if (index > -1) {
  19378. this._geometries.splice(index, 1);
  19379. //notify the collision coordinator
  19380. if (this.collisionCoordinator) {
  19381. this.collisionCoordinator.onGeometryDeleted(geometry);
  19382. }
  19383. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19384. return true;
  19385. }
  19386. return false;
  19387. };
  19388. Scene.prototype.getGeometries = function () {
  19389. return this._geometries;
  19390. };
  19391. /**
  19392. * Get the first added mesh found of a given ID
  19393. * @param {string} id - the id to search for
  19394. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19395. */
  19396. Scene.prototype.getMeshByID = function (id) {
  19397. for (var index = 0; index < this.meshes.length; index++) {
  19398. if (this.meshes[index].id === id) {
  19399. return this.meshes[index];
  19400. }
  19401. }
  19402. return null;
  19403. };
  19404. Scene.prototype.getMeshesByID = function (id) {
  19405. return this.meshes.filter(function (m) {
  19406. return m.id === id;
  19407. });
  19408. };
  19409. /**
  19410. * Get a mesh with its auto-generated unique id
  19411. * @param {number} uniqueId - the unique id to search for
  19412. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19413. */
  19414. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19415. for (var index = 0; index < this.meshes.length; index++) {
  19416. if (this.meshes[index].uniqueId === uniqueId) {
  19417. return this.meshes[index];
  19418. }
  19419. }
  19420. return null;
  19421. };
  19422. /**
  19423. * Get a the last added mesh found of a given ID
  19424. * @param {string} id - the id to search for
  19425. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19426. */
  19427. Scene.prototype.getLastMeshByID = function (id) {
  19428. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19429. if (this.meshes[index].id === id) {
  19430. return this.meshes[index];
  19431. }
  19432. }
  19433. return null;
  19434. };
  19435. /**
  19436. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19437. * @param {string} id - the id to search for
  19438. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19439. */
  19440. Scene.prototype.getLastEntryByID = function (id) {
  19441. var index;
  19442. for (index = this.meshes.length - 1; index >= 0; index--) {
  19443. if (this.meshes[index].id === id) {
  19444. return this.meshes[index];
  19445. }
  19446. }
  19447. for (index = this.cameras.length - 1; index >= 0; index--) {
  19448. if (this.cameras[index].id === id) {
  19449. return this.cameras[index];
  19450. }
  19451. }
  19452. for (index = this.lights.length - 1; index >= 0; index--) {
  19453. if (this.lights[index].id === id) {
  19454. return this.lights[index];
  19455. }
  19456. }
  19457. return null;
  19458. };
  19459. Scene.prototype.getNodeByID = function (id) {
  19460. var mesh = this.getMeshByID(id);
  19461. if (mesh) {
  19462. return mesh;
  19463. }
  19464. var light = this.getLightByID(id);
  19465. if (light) {
  19466. return light;
  19467. }
  19468. var camera = this.getCameraByID(id);
  19469. if (camera) {
  19470. return camera;
  19471. }
  19472. var bone = this.getBoneByID(id);
  19473. return bone;
  19474. };
  19475. Scene.prototype.getNodeByName = function (name) {
  19476. var mesh = this.getMeshByName(name);
  19477. if (mesh) {
  19478. return mesh;
  19479. }
  19480. var light = this.getLightByName(name);
  19481. if (light) {
  19482. return light;
  19483. }
  19484. var camera = this.getCameraByName(name);
  19485. if (camera) {
  19486. return camera;
  19487. }
  19488. var bone = this.getBoneByName(name);
  19489. return bone;
  19490. };
  19491. Scene.prototype.getMeshByName = function (name) {
  19492. for (var index = 0; index < this.meshes.length; index++) {
  19493. if (this.meshes[index].name === name) {
  19494. return this.meshes[index];
  19495. }
  19496. }
  19497. return null;
  19498. };
  19499. Scene.prototype.getSoundByName = function (name) {
  19500. var index;
  19501. if (BABYLON.AudioEngine) {
  19502. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19503. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19504. return this.mainSoundTrack.soundCollection[index];
  19505. }
  19506. }
  19507. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19508. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19509. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19510. return this.soundTracks[sdIndex].soundCollection[index];
  19511. }
  19512. }
  19513. }
  19514. }
  19515. return null;
  19516. };
  19517. Scene.prototype.getLastSkeletonByID = function (id) {
  19518. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19519. if (this.skeletons[index].id === id) {
  19520. return this.skeletons[index];
  19521. }
  19522. }
  19523. return null;
  19524. };
  19525. Scene.prototype.getSkeletonById = function (id) {
  19526. for (var index = 0; index < this.skeletons.length; index++) {
  19527. if (this.skeletons[index].id === id) {
  19528. return this.skeletons[index];
  19529. }
  19530. }
  19531. return null;
  19532. };
  19533. Scene.prototype.getSkeletonByName = function (name) {
  19534. for (var index = 0; index < this.skeletons.length; index++) {
  19535. if (this.skeletons[index].name === name) {
  19536. return this.skeletons[index];
  19537. }
  19538. }
  19539. return null;
  19540. };
  19541. Scene.prototype.getMorphTargetManagerById = function (id) {
  19542. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19543. if (this.morphTargetManagers[index].uniqueId === id) {
  19544. return this.morphTargetManagers[index];
  19545. }
  19546. }
  19547. return null;
  19548. };
  19549. Scene.prototype.isActiveMesh = function (mesh) {
  19550. return (this._activeMeshes.indexOf(mesh) !== -1);
  19551. };
  19552. /**
  19553. * Return a the first highlight layer of the scene with a given name.
  19554. * @param name The name of the highlight layer to look for.
  19555. * @return The highlight layer if found otherwise null.
  19556. */
  19557. Scene.prototype.getHighlightLayerByName = function (name) {
  19558. for (var index = 0; index < this.highlightLayers.length; index++) {
  19559. if (this.highlightLayers[index].name === name) {
  19560. return this.highlightLayers[index];
  19561. }
  19562. }
  19563. return null;
  19564. };
  19565. Object.defineProperty(Scene.prototype, "uid", {
  19566. /**
  19567. * Return a unique id as a string which can serve as an identifier for the scene
  19568. */
  19569. get: function () {
  19570. if (!this._uid) {
  19571. this._uid = BABYLON.Tools.RandomId();
  19572. }
  19573. return this._uid;
  19574. },
  19575. enumerable: true,
  19576. configurable: true
  19577. });
  19578. /**
  19579. * Add an externaly attached data from its key.
  19580. * This method call will fail and return false, if such key already exists.
  19581. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19582. * @param key the unique key that identifies the data
  19583. * @param data the data object to associate to the key for this Engine instance
  19584. * @return true if no such key were already present and the data was added successfully, false otherwise
  19585. */
  19586. Scene.prototype.addExternalData = function (key, data) {
  19587. if (!this._externalData) {
  19588. this._externalData = new BABYLON.StringDictionary();
  19589. }
  19590. return this._externalData.add(key, data);
  19591. };
  19592. /**
  19593. * Get an externaly attached data from its key
  19594. * @param key the unique key that identifies the data
  19595. * @return the associated data, if present (can be null), or undefined if not present
  19596. */
  19597. Scene.prototype.getExternalData = function (key) {
  19598. if (!this._externalData) {
  19599. return null;
  19600. }
  19601. return this._externalData.get(key);
  19602. };
  19603. /**
  19604. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19605. * @param key the unique key that identifies the data
  19606. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19607. * @return the associated data, can be null if the factory returned null.
  19608. */
  19609. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19610. if (!this._externalData) {
  19611. this._externalData = new BABYLON.StringDictionary();
  19612. }
  19613. return this._externalData.getOrAddWithFactory(key, factory);
  19614. };
  19615. /**
  19616. * Remove an externaly attached data from the Engine instance
  19617. * @param key the unique key that identifies the data
  19618. * @return true if the data was successfully removed, false if it doesn't exist
  19619. */
  19620. Scene.prototype.removeExternalData = function (key) {
  19621. return this._externalData.remove(key);
  19622. };
  19623. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19624. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19625. var material = subMesh.getMaterial();
  19626. if (mesh.showSubMeshesBoundingBox) {
  19627. var boundingInfo = subMesh.getBoundingInfo();
  19628. if (boundingInfo) {
  19629. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19630. }
  19631. }
  19632. if (material) {
  19633. // Render targets
  19634. if (material.getRenderTargetTextures) {
  19635. if (this._processedMaterials.indexOf(material) === -1) {
  19636. this._processedMaterials.push(material);
  19637. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19638. }
  19639. }
  19640. // Dispatch
  19641. this._activeIndices.addCount(subMesh.indexCount, false);
  19642. this._renderingManager.dispatch(subMesh);
  19643. }
  19644. }
  19645. };
  19646. Scene.prototype._isInIntermediateRendering = function () {
  19647. return this._intermediateRendering;
  19648. };
  19649. /**
  19650. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19651. */
  19652. Scene.prototype.freezeActiveMeshes = function () {
  19653. this._evaluateActiveMeshes();
  19654. this._activeMeshesFrozen = true;
  19655. return this;
  19656. };
  19657. /**
  19658. * Use this function to restart evaluating active meshes on every frame
  19659. */
  19660. Scene.prototype.unfreezeActiveMeshes = function () {
  19661. this._activeMeshesFrozen = false;
  19662. return this;
  19663. };
  19664. Scene.prototype._evaluateActiveMeshes = function () {
  19665. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19666. return;
  19667. }
  19668. if (!this.activeCamera) {
  19669. return;
  19670. }
  19671. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19672. this.activeCamera._activeMeshes.reset();
  19673. this._activeMeshes.reset();
  19674. this._renderingManager.reset();
  19675. this._processedMaterials.reset();
  19676. this._activeParticleSystems.reset();
  19677. this._activeSkeletons.reset();
  19678. this._softwareSkinnedMeshes.reset();
  19679. if (this._boundingBoxRenderer) {
  19680. this._boundingBoxRenderer.reset();
  19681. }
  19682. // Meshes
  19683. var meshes;
  19684. var len;
  19685. if (this._selectionOctree) {
  19686. var selection = this._selectionOctree.select(this._frustumPlanes);
  19687. meshes = selection.data;
  19688. len = selection.length;
  19689. }
  19690. else {
  19691. len = this.meshes.length;
  19692. meshes = this.meshes;
  19693. }
  19694. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19695. var mesh = meshes[meshIndex];
  19696. if (mesh.isBlocked) {
  19697. continue;
  19698. }
  19699. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19700. if (!mesh.isReady() || !mesh.isEnabled()) {
  19701. continue;
  19702. }
  19703. mesh.computeWorldMatrix();
  19704. // Intersections
  19705. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19706. this._meshesForIntersections.pushNoDuplicate(mesh);
  19707. }
  19708. // Switch to current LOD
  19709. var meshLOD = mesh.getLOD(this.activeCamera);
  19710. if (!meshLOD) {
  19711. continue;
  19712. }
  19713. mesh._preActivate();
  19714. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19715. this._activeMeshes.push(mesh);
  19716. this.activeCamera._activeMeshes.push(mesh);
  19717. mesh._activate(this._renderId);
  19718. if (meshLOD !== mesh) {
  19719. meshLOD._activate(this._renderId);
  19720. }
  19721. this._activeMesh(mesh, meshLOD);
  19722. }
  19723. }
  19724. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19725. // Particle systems
  19726. if (this.particlesEnabled) {
  19727. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19728. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19729. var particleSystem = this.particleSystems[particleIndex];
  19730. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19731. continue;
  19732. }
  19733. var emitter = particleSystem.emitter;
  19734. if (!emitter.position || emitter.isEnabled()) {
  19735. this._activeParticleSystems.push(particleSystem);
  19736. particleSystem.animate();
  19737. this._renderingManager.dispatchParticles(particleSystem);
  19738. }
  19739. }
  19740. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19741. }
  19742. };
  19743. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19744. if (mesh.skeleton && this.skeletonsEnabled) {
  19745. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19746. mesh.skeleton.prepare();
  19747. }
  19748. if (!mesh.computeBonesUsingShaders) {
  19749. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19750. }
  19751. }
  19752. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19753. var boundingInfo = sourceMesh.getBoundingInfo();
  19754. if (boundingInfo) {
  19755. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19756. }
  19757. }
  19758. if (mesh && mesh.subMeshes) {
  19759. // Submeshes Octrees
  19760. var len;
  19761. var subMeshes;
  19762. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19763. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19764. len = intersections.length;
  19765. subMeshes = intersections.data;
  19766. }
  19767. else {
  19768. subMeshes = mesh.subMeshes;
  19769. len = subMeshes.length;
  19770. }
  19771. for (var subIndex = 0; subIndex < len; subIndex++) {
  19772. var subMesh = subMeshes[subIndex];
  19773. this._evaluateSubMesh(subMesh, mesh);
  19774. }
  19775. }
  19776. };
  19777. Scene.prototype.updateTransformMatrix = function (force) {
  19778. if (!this.activeCamera) {
  19779. return;
  19780. }
  19781. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19782. };
  19783. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19784. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19785. };
  19786. Scene.prototype._renderForCamera = function (camera) {
  19787. if (camera && camera._skipRendering) {
  19788. return;
  19789. }
  19790. var engine = this._engine;
  19791. this.activeCamera = camera;
  19792. if (!this.activeCamera)
  19793. throw new Error("Active camera not set");
  19794. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19795. // Viewport
  19796. engine.setViewport(this.activeCamera.viewport);
  19797. // Camera
  19798. this.resetCachedMaterial();
  19799. this._renderId++;
  19800. this.activeCamera.update();
  19801. this.updateTransformMatrix();
  19802. if (camera._alternateCamera) {
  19803. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19804. this._alternateRendering = true;
  19805. }
  19806. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19807. // Meshes
  19808. this._evaluateActiveMeshes();
  19809. // Software skinning
  19810. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19811. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19812. mesh.applySkeleton(mesh.skeleton);
  19813. }
  19814. // Render targets
  19815. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19816. var needsRestoreFrameBuffer = false;
  19817. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19818. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19819. }
  19820. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19821. this._intermediateRendering = true;
  19822. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19823. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19824. var renderTarget = this._renderTargets.data[renderIndex];
  19825. if (renderTarget._shouldRender()) {
  19826. this._renderId++;
  19827. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19828. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19829. }
  19830. }
  19831. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19832. this._intermediateRendering = false;
  19833. this._renderId++;
  19834. needsRestoreFrameBuffer = true; // Restore back buffer
  19835. }
  19836. // Render HighlightLayer Texture
  19837. var stencilState = this._engine.getStencilBuffer();
  19838. var renderhighlights = false;
  19839. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19840. this._intermediateRendering = true;
  19841. for (var i = 0; i < this.highlightLayers.length; i++) {
  19842. var highlightLayer = this.highlightLayers[i];
  19843. if (highlightLayer.shouldRender() &&
  19844. (!highlightLayer.camera ||
  19845. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19846. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19847. renderhighlights = true;
  19848. var renderTarget = highlightLayer._mainTexture;
  19849. if (renderTarget._shouldRender()) {
  19850. this._renderId++;
  19851. renderTarget.render(false, false);
  19852. needsRestoreFrameBuffer = true;
  19853. }
  19854. }
  19855. }
  19856. this._intermediateRendering = false;
  19857. this._renderId++;
  19858. }
  19859. if (needsRestoreFrameBuffer) {
  19860. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19861. }
  19862. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19863. // Prepare Frame
  19864. this.postProcessManager._prepareFrame();
  19865. // Backgrounds
  19866. var layerIndex;
  19867. var layer;
  19868. if (this.layers.length) {
  19869. engine.setDepthBuffer(false);
  19870. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19871. layer = this.layers[layerIndex];
  19872. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19873. layer.render();
  19874. }
  19875. }
  19876. engine.setDepthBuffer(true);
  19877. }
  19878. // Activate HighlightLayer stencil
  19879. if (renderhighlights) {
  19880. this._engine.setStencilBuffer(true);
  19881. }
  19882. // Render
  19883. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  19884. this._renderingManager.render(null, null, true, true);
  19885. this.onAfterDrawPhaseObservable.notifyObservers(this);
  19886. // Restore HighlightLayer stencil
  19887. if (renderhighlights) {
  19888. this._engine.setStencilBuffer(stencilState);
  19889. }
  19890. // Bounding boxes
  19891. if (this._boundingBoxRenderer) {
  19892. this._boundingBoxRenderer.render();
  19893. }
  19894. // Lens flares
  19895. if (this.lensFlaresEnabled) {
  19896. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19897. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19898. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19899. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19900. lensFlareSystem.render();
  19901. }
  19902. }
  19903. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19904. }
  19905. // Foregrounds
  19906. if (this.layers.length) {
  19907. engine.setDepthBuffer(false);
  19908. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19909. layer = this.layers[layerIndex];
  19910. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19911. layer.render();
  19912. }
  19913. }
  19914. engine.setDepthBuffer(true);
  19915. }
  19916. // Highlight Layer
  19917. if (renderhighlights) {
  19918. engine.setDepthBuffer(false);
  19919. for (var i = 0; i < this.highlightLayers.length; i++) {
  19920. if (this.highlightLayers[i].shouldRender()) {
  19921. this.highlightLayers[i].render();
  19922. }
  19923. }
  19924. engine.setDepthBuffer(true);
  19925. }
  19926. // Finalize frame
  19927. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19928. // Reset some special arrays
  19929. this._renderTargets.reset();
  19930. this._alternateRendering = false;
  19931. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19932. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19933. };
  19934. Scene.prototype._processSubCameras = function (camera) {
  19935. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19936. this._renderForCamera(camera);
  19937. return;
  19938. }
  19939. // Update camera
  19940. if (this.activeCamera) {
  19941. this.activeCamera.update();
  19942. }
  19943. // rig cameras
  19944. for (var index = 0; index < camera._rigCameras.length; index++) {
  19945. this._renderForCamera(camera._rigCameras[index]);
  19946. }
  19947. this.activeCamera = camera;
  19948. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19949. };
  19950. Scene.prototype._checkIntersections = function () {
  19951. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19952. var sourceMesh = this._meshesForIntersections.data[index];
  19953. if (!sourceMesh.actionManager) {
  19954. continue;
  19955. }
  19956. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19957. var action = sourceMesh.actionManager.actions[actionIndex];
  19958. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19959. var parameters = action.getTriggerParameter();
  19960. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19961. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19962. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19963. if (areIntersecting && currentIntersectionInProgress === -1) {
  19964. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19965. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19966. sourceMesh._intersectionsInProgress.push(otherMesh);
  19967. }
  19968. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19969. sourceMesh._intersectionsInProgress.push(otherMesh);
  19970. }
  19971. }
  19972. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19973. //They intersected, and now they don't.
  19974. //is this trigger an exit trigger? execute an event.
  19975. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19976. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19977. }
  19978. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19979. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19980. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19981. }
  19982. }
  19983. }
  19984. }
  19985. }
  19986. };
  19987. Scene.prototype.render = function () {
  19988. if (this.isDisposed) {
  19989. return;
  19990. }
  19991. this._activeParticles.fetchNewFrame();
  19992. this._totalVertices.fetchNewFrame();
  19993. this._activeIndices.fetchNewFrame();
  19994. this._activeBones.fetchNewFrame();
  19995. this._meshesForIntersections.reset();
  19996. this.resetCachedMaterial();
  19997. this.onBeforeAnimationsObservable.notifyObservers(this);
  19998. // Actions
  19999. if (this.actionManager) {
  20000. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20001. }
  20002. //Simplification Queue
  20003. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20004. this.simplificationQueue.executeNext();
  20005. }
  20006. if (this._engine.isDeterministicLockStep()) {
  20007. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  20008. var defaultTimeStep = (60.0 / 1000.0);
  20009. if (this._physicsEngine) {
  20010. defaultTimeStep = this._physicsEngine.getTimeStep();
  20011. }
  20012. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20013. this._timeAccumulator += deltaTime;
  20014. // compute the amount of fixed steps we should have taken since the last step
  20015. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20016. internalSteps = Math.min(internalSteps, maxSubSteps);
  20017. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20018. this.onBeforeStepObservable.notifyObservers(this);
  20019. // Animations
  20020. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20021. this._animate();
  20022. this.onAfterAnimationsObservable.notifyObservers(this);
  20023. // Physics
  20024. if (this._physicsEngine) {
  20025. this.onBeforePhysicsObservable.notifyObservers(this);
  20026. this._physicsEngine._step(defaultTimeStep);
  20027. this.onAfterPhysicsObservable.notifyObservers(this);
  20028. }
  20029. this._timeAccumulator -= defaultTimeStep;
  20030. this.onAfterStepObservable.notifyObservers(this);
  20031. this._currentStepId++;
  20032. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20033. this._evaluateActiveMeshes();
  20034. }
  20035. }
  20036. }
  20037. else {
  20038. // Animations
  20039. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20040. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20041. this._animate();
  20042. this.onAfterAnimationsObservable.notifyObservers(this);
  20043. // Physics
  20044. if (this._physicsEngine) {
  20045. this.onBeforePhysicsObservable.notifyObservers(this);
  20046. this._physicsEngine._step(deltaTime / 1000.0);
  20047. this.onAfterPhysicsObservable.notifyObservers(this);
  20048. }
  20049. }
  20050. // Before render
  20051. this.onBeforeRenderObservable.notifyObservers(this);
  20052. // Customs render targets
  20053. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20054. var engine = this.getEngine();
  20055. var currentActiveCamera = this.activeCamera;
  20056. if (this.renderTargetsEnabled) {
  20057. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20058. this._intermediateRendering = true;
  20059. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20060. var renderTarget = this.customRenderTargets[customIndex];
  20061. if (renderTarget._shouldRender()) {
  20062. this._renderId++;
  20063. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20064. if (!this.activeCamera)
  20065. throw new Error("Active camera not set");
  20066. // Viewport
  20067. engine.setViewport(this.activeCamera.viewport);
  20068. // Camera
  20069. this.updateTransformMatrix();
  20070. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20071. }
  20072. }
  20073. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20074. this._intermediateRendering = false;
  20075. this._renderId++;
  20076. }
  20077. // Restore back buffer
  20078. if (this.customRenderTargets.length > 0) {
  20079. engine.restoreDefaultFramebuffer();
  20080. }
  20081. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20082. this.activeCamera = currentActiveCamera;
  20083. // Procedural textures
  20084. if (this.proceduralTexturesEnabled) {
  20085. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20086. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20087. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20088. if (proceduralTexture._shouldRender()) {
  20089. proceduralTexture.render();
  20090. }
  20091. }
  20092. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20093. }
  20094. // Clear
  20095. if (this.autoClearDepthAndStencil || this.autoClear) {
  20096. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20097. }
  20098. // Shadows
  20099. if (this.shadowsEnabled) {
  20100. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20101. var light = this.lights[lightIndex];
  20102. var shadowGenerator = light.getShadowGenerator();
  20103. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20104. var shadowMap = (shadowGenerator.getShadowMap());
  20105. if (this.textures.indexOf(shadowMap) !== -1) {
  20106. this._renderTargets.push(shadowMap);
  20107. }
  20108. }
  20109. }
  20110. }
  20111. // Depth renderer
  20112. if (this._depthRenderer) {
  20113. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20114. }
  20115. // Geometry renderer
  20116. if (this._geometryBufferRenderer) {
  20117. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20118. }
  20119. // RenderPipeline
  20120. if (this._postProcessRenderPipelineManager) {
  20121. this._postProcessRenderPipelineManager.update();
  20122. }
  20123. // Multi-cameras?
  20124. if (this.activeCameras.length > 0) {
  20125. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20126. if (cameraIndex > 0) {
  20127. this._engine.clear(null, false, true, true);
  20128. }
  20129. this._processSubCameras(this.activeCameras[cameraIndex]);
  20130. }
  20131. }
  20132. else {
  20133. if (!this.activeCamera) {
  20134. throw new Error("No camera defined");
  20135. }
  20136. this._processSubCameras(this.activeCamera);
  20137. }
  20138. // Intersection checks
  20139. this._checkIntersections();
  20140. // Update the audio listener attached to the camera
  20141. if (BABYLON.AudioEngine) {
  20142. this._updateAudioParameters();
  20143. }
  20144. // After render
  20145. if (this.afterRender) {
  20146. this.afterRender();
  20147. }
  20148. this.onAfterRenderObservable.notifyObservers(this);
  20149. // Cleaning
  20150. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20151. var data = this._toBeDisposed.data[index];
  20152. if (data) {
  20153. data.dispose();
  20154. }
  20155. this._toBeDisposed[index] = null;
  20156. }
  20157. this._toBeDisposed.reset();
  20158. if (this.dumpNextRenderTargets) {
  20159. this.dumpNextRenderTargets = false;
  20160. }
  20161. this._activeBones.addCount(0, true);
  20162. this._activeIndices.addCount(0, true);
  20163. this._activeParticles.addCount(0, true);
  20164. };
  20165. Scene.prototype._updateAudioParameters = function () {
  20166. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20167. return;
  20168. }
  20169. var listeningCamera;
  20170. var audioEngine = BABYLON.Engine.audioEngine;
  20171. if (this.activeCameras.length > 0) {
  20172. listeningCamera = this.activeCameras[0];
  20173. }
  20174. else {
  20175. listeningCamera = this.activeCamera;
  20176. }
  20177. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20178. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20179. // for VR cameras
  20180. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20181. listeningCamera = listeningCamera.rigCameras[0];
  20182. }
  20183. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20184. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20185. cameraDirection.normalize();
  20186. // To avoid some errors on GearVR
  20187. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20188. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20189. }
  20190. var i;
  20191. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20192. var sound = this.mainSoundTrack.soundCollection[i];
  20193. if (sound.useCustomAttenuation) {
  20194. sound.updateDistanceFromListener();
  20195. }
  20196. }
  20197. for (i = 0; i < this.soundTracks.length; i++) {
  20198. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20199. sound = this.soundTracks[i].soundCollection[j];
  20200. if (sound.useCustomAttenuation) {
  20201. sound.updateDistanceFromListener();
  20202. }
  20203. }
  20204. }
  20205. }
  20206. };
  20207. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20208. // Audio
  20209. get: function () {
  20210. return this._audioEnabled;
  20211. },
  20212. set: function (value) {
  20213. this._audioEnabled = value;
  20214. if (BABYLON.AudioEngine) {
  20215. if (this._audioEnabled) {
  20216. this._enableAudio();
  20217. }
  20218. else {
  20219. this._disableAudio();
  20220. }
  20221. }
  20222. },
  20223. enumerable: true,
  20224. configurable: true
  20225. });
  20226. Scene.prototype._disableAudio = function () {
  20227. var i;
  20228. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20229. this.mainSoundTrack.soundCollection[i].pause();
  20230. }
  20231. for (i = 0; i < this.soundTracks.length; i++) {
  20232. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20233. this.soundTracks[i].soundCollection[j].pause();
  20234. }
  20235. }
  20236. };
  20237. Scene.prototype._enableAudio = function () {
  20238. var i;
  20239. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20240. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20241. this.mainSoundTrack.soundCollection[i].play();
  20242. }
  20243. }
  20244. for (i = 0; i < this.soundTracks.length; i++) {
  20245. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20246. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20247. this.soundTracks[i].soundCollection[j].play();
  20248. }
  20249. }
  20250. }
  20251. };
  20252. Object.defineProperty(Scene.prototype, "headphone", {
  20253. get: function () {
  20254. return this._headphone;
  20255. },
  20256. set: function (value) {
  20257. this._headphone = value;
  20258. if (BABYLON.AudioEngine) {
  20259. if (this._headphone) {
  20260. this._switchAudioModeForHeadphones();
  20261. }
  20262. else {
  20263. this._switchAudioModeForNormalSpeakers();
  20264. }
  20265. }
  20266. },
  20267. enumerable: true,
  20268. configurable: true
  20269. });
  20270. Scene.prototype._switchAudioModeForHeadphones = function () {
  20271. this.mainSoundTrack.switchPanningModelToHRTF();
  20272. for (var i = 0; i < this.soundTracks.length; i++) {
  20273. this.soundTracks[i].switchPanningModelToHRTF();
  20274. }
  20275. };
  20276. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20277. this.mainSoundTrack.switchPanningModelToEqualPower();
  20278. for (var i = 0; i < this.soundTracks.length; i++) {
  20279. this.soundTracks[i].switchPanningModelToEqualPower();
  20280. }
  20281. };
  20282. Scene.prototype.enableDepthRenderer = function () {
  20283. if (this._depthRenderer) {
  20284. return this._depthRenderer;
  20285. }
  20286. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20287. return this._depthRenderer;
  20288. };
  20289. Scene.prototype.disableDepthRenderer = function () {
  20290. if (!this._depthRenderer) {
  20291. return;
  20292. }
  20293. this._depthRenderer.dispose();
  20294. this._depthRenderer = null;
  20295. };
  20296. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20297. if (ratio === void 0) { ratio = 1; }
  20298. if (this._geometryBufferRenderer) {
  20299. return this._geometryBufferRenderer;
  20300. }
  20301. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20302. if (!this._geometryBufferRenderer.isSupported) {
  20303. this._geometryBufferRenderer = null;
  20304. }
  20305. return this._geometryBufferRenderer;
  20306. };
  20307. Scene.prototype.disableGeometryBufferRenderer = function () {
  20308. if (!this._geometryBufferRenderer) {
  20309. return;
  20310. }
  20311. this._geometryBufferRenderer.dispose();
  20312. this._geometryBufferRenderer = null;
  20313. };
  20314. Scene.prototype.freezeMaterials = function () {
  20315. for (var i = 0; i < this.materials.length; i++) {
  20316. this.materials[i].freeze();
  20317. }
  20318. };
  20319. Scene.prototype.unfreezeMaterials = function () {
  20320. for (var i = 0; i < this.materials.length; i++) {
  20321. this.materials[i].unfreeze();
  20322. }
  20323. };
  20324. Scene.prototype.dispose = function () {
  20325. this.beforeRender = null;
  20326. this.afterRender = null;
  20327. this.skeletons = [];
  20328. this.morphTargetManagers = [];
  20329. this.importedMeshesFiles = new Array();
  20330. this.resetCachedMaterial();
  20331. if (this._depthRenderer) {
  20332. this._depthRenderer.dispose();
  20333. }
  20334. if (this._gamepadManager) {
  20335. this._gamepadManager.dispose();
  20336. this._gamepadManager = null;
  20337. }
  20338. // Smart arrays
  20339. if (this.activeCamera) {
  20340. this.activeCamera._activeMeshes.dispose();
  20341. this.activeCamera = null;
  20342. }
  20343. this._activeMeshes.dispose();
  20344. this._renderingManager.dispose();
  20345. this._processedMaterials.dispose();
  20346. this._activeParticleSystems.dispose();
  20347. this._activeSkeletons.dispose();
  20348. this._softwareSkinnedMeshes.dispose();
  20349. this._renderTargets.dispose();
  20350. if (this._boundingBoxRenderer) {
  20351. this._boundingBoxRenderer.dispose();
  20352. }
  20353. this._meshesForIntersections.dispose();
  20354. this._toBeDisposed.dispose();
  20355. // Debug layer
  20356. if (this._debugLayer) {
  20357. this._debugLayer.hide();
  20358. }
  20359. // Events
  20360. this.onDisposeObservable.notifyObservers(this);
  20361. this.onDisposeObservable.clear();
  20362. this.onBeforeRenderObservable.clear();
  20363. this.onAfterRenderObservable.clear();
  20364. this.OnBeforeRenderTargetsRenderObservable.clear();
  20365. this.OnAfterRenderTargetsRenderObservable.clear();
  20366. this.onAfterStepObservable.clear();
  20367. this.onBeforeStepObservable.clear();
  20368. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20369. this.onAfterActiveMeshesEvaluationObservable.clear();
  20370. this.onBeforeParticlesRenderingObservable.clear();
  20371. this.onAfterParticlesRenderingObservable.clear();
  20372. this.onBeforeSpritesRenderingObservable.clear();
  20373. this.onAfterSpritesRenderingObservable.clear();
  20374. this.onBeforeDrawPhaseObservable.clear();
  20375. this.onAfterDrawPhaseObservable.clear();
  20376. this.onBeforePhysicsObservable.clear();
  20377. this.onAfterPhysicsObservable.clear();
  20378. this.onBeforeAnimationsObservable.clear();
  20379. this.onAfterAnimationsObservable.clear();
  20380. this.detachControl();
  20381. // Release sounds & sounds tracks
  20382. if (BABYLON.AudioEngine) {
  20383. this.disposeSounds();
  20384. }
  20385. // VR Helper
  20386. if (this.VRHelper) {
  20387. this.VRHelper.dispose();
  20388. }
  20389. // Detach cameras
  20390. var canvas = this._engine.getRenderingCanvas();
  20391. if (canvas) {
  20392. var index;
  20393. for (index = 0; index < this.cameras.length; index++) {
  20394. this.cameras[index].detachControl(canvas);
  20395. }
  20396. }
  20397. // Release lights
  20398. while (this.lights.length) {
  20399. this.lights[0].dispose();
  20400. }
  20401. // Release meshes
  20402. while (this.meshes.length) {
  20403. this.meshes[0].dispose(true);
  20404. }
  20405. // Release cameras
  20406. while (this.cameras.length) {
  20407. this.cameras[0].dispose();
  20408. }
  20409. // Release materials
  20410. if (this.defaultMaterial) {
  20411. this.defaultMaterial.dispose();
  20412. }
  20413. while (this.multiMaterials.length) {
  20414. this.multiMaterials[0].dispose();
  20415. }
  20416. while (this.materials.length) {
  20417. this.materials[0].dispose();
  20418. }
  20419. // Release particles
  20420. while (this.particleSystems.length) {
  20421. this.particleSystems[0].dispose();
  20422. }
  20423. // Release sprites
  20424. while (this.spriteManagers.length) {
  20425. this.spriteManagers[0].dispose();
  20426. }
  20427. // Release postProcesses
  20428. while (this.postProcesses.length) {
  20429. this.postProcesses[0].dispose();
  20430. }
  20431. // Release layers
  20432. while (this.layers.length) {
  20433. this.layers[0].dispose();
  20434. }
  20435. while (this.highlightLayers.length) {
  20436. this.highlightLayers[0].dispose();
  20437. }
  20438. // Release textures
  20439. while (this.textures.length) {
  20440. this.textures[0].dispose();
  20441. }
  20442. // Release UBO
  20443. this._sceneUbo.dispose();
  20444. if (this._alternateSceneUbo) {
  20445. this._alternateSceneUbo.dispose();
  20446. }
  20447. // Post-processes
  20448. this.postProcessManager.dispose();
  20449. if (this._postProcessRenderPipelineManager) {
  20450. this._postProcessRenderPipelineManager.dispose();
  20451. }
  20452. // Physics
  20453. if (this._physicsEngine) {
  20454. this.disablePhysicsEngine();
  20455. }
  20456. // Remove from engine
  20457. index = this._engine.scenes.indexOf(this);
  20458. if (index > -1) {
  20459. this._engine.scenes.splice(index, 1);
  20460. }
  20461. this._engine.wipeCaches();
  20462. this._isDisposed = true;
  20463. };
  20464. Object.defineProperty(Scene.prototype, "isDisposed", {
  20465. get: function () {
  20466. return this._isDisposed;
  20467. },
  20468. enumerable: true,
  20469. configurable: true
  20470. });
  20471. // Release sounds & sounds tracks
  20472. Scene.prototype.disposeSounds = function () {
  20473. if (!this._mainSoundTrack) {
  20474. return;
  20475. }
  20476. this.mainSoundTrack.dispose();
  20477. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20478. this.soundTracks[scIndex].dispose();
  20479. }
  20480. };
  20481. // Octrees
  20482. Scene.prototype.getWorldExtends = function () {
  20483. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20484. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20485. for (var index = 0; index < this.meshes.length; index++) {
  20486. var mesh = this.meshes[index];
  20487. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20488. continue;
  20489. }
  20490. mesh.computeWorldMatrix(true);
  20491. var boundingInfo = mesh.getBoundingInfo();
  20492. if (boundingInfo) {
  20493. var minBox = boundingInfo.boundingBox.minimumWorld;
  20494. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20495. BABYLON.Tools.CheckExtends(minBox, min, max);
  20496. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20497. }
  20498. }
  20499. return {
  20500. min: min,
  20501. max: max
  20502. };
  20503. };
  20504. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20505. if (maxCapacity === void 0) { maxCapacity = 64; }
  20506. if (maxDepth === void 0) { maxDepth = 2; }
  20507. if (!this._selectionOctree) {
  20508. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20509. }
  20510. var worldExtends = this.getWorldExtends();
  20511. // Update octree
  20512. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20513. return this._selectionOctree;
  20514. };
  20515. // Picking
  20516. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20517. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20518. var engine = this._engine;
  20519. if (!camera) {
  20520. if (!this.activeCamera)
  20521. throw new Error("Active camera not set");
  20522. camera = this.activeCamera;
  20523. }
  20524. var cameraViewport = camera.viewport;
  20525. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20526. // Moving coordinates to local viewport world
  20527. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20528. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20529. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20530. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20531. };
  20532. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20533. if (!BABYLON.PickingInfo) {
  20534. return null;
  20535. }
  20536. var engine = this._engine;
  20537. if (!camera) {
  20538. if (!this.activeCamera)
  20539. throw new Error("Active camera not set");
  20540. camera = this.activeCamera;
  20541. }
  20542. var cameraViewport = camera.viewport;
  20543. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20544. var identity = BABYLON.Matrix.Identity();
  20545. // Moving coordinates to local viewport world
  20546. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20547. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20548. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20549. };
  20550. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20551. if (!BABYLON.PickingInfo) {
  20552. return null;
  20553. }
  20554. var pickingInfo = null;
  20555. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20556. var mesh = this.meshes[meshIndex];
  20557. if (predicate) {
  20558. if (!predicate(mesh)) {
  20559. continue;
  20560. }
  20561. }
  20562. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20563. continue;
  20564. }
  20565. var world = mesh.getWorldMatrix();
  20566. var ray = rayFunction(world);
  20567. var result = mesh.intersects(ray, fastCheck);
  20568. if (!result || !result.hit)
  20569. continue;
  20570. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20571. continue;
  20572. pickingInfo = result;
  20573. if (fastCheck) {
  20574. break;
  20575. }
  20576. }
  20577. return pickingInfo || new BABYLON.PickingInfo();
  20578. };
  20579. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20580. if (!BABYLON.PickingInfo) {
  20581. return null;
  20582. }
  20583. var pickingInfos = new Array();
  20584. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20585. var mesh = this.meshes[meshIndex];
  20586. if (predicate) {
  20587. if (!predicate(mesh)) {
  20588. continue;
  20589. }
  20590. }
  20591. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20592. continue;
  20593. }
  20594. var world = mesh.getWorldMatrix();
  20595. var ray = rayFunction(world);
  20596. var result = mesh.intersects(ray, false);
  20597. if (!result || !result.hit)
  20598. continue;
  20599. pickingInfos.push(result);
  20600. }
  20601. return pickingInfos;
  20602. };
  20603. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20604. if (!BABYLON.PickingInfo) {
  20605. return null;
  20606. }
  20607. var pickingInfo = null;
  20608. if (!camera) {
  20609. if (!this.activeCamera) {
  20610. return null;
  20611. }
  20612. camera = this.activeCamera;
  20613. }
  20614. if (this.spriteManagers.length > 0) {
  20615. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20616. var spriteManager = this.spriteManagers[spriteIndex];
  20617. if (!spriteManager.isPickable) {
  20618. continue;
  20619. }
  20620. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20621. if (!result || !result.hit)
  20622. continue;
  20623. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20624. continue;
  20625. pickingInfo = result;
  20626. if (fastCheck) {
  20627. break;
  20628. }
  20629. }
  20630. }
  20631. return pickingInfo || new BABYLON.PickingInfo();
  20632. };
  20633. /** Launch a ray to try to pick a mesh in the scene
  20634. * @param x position on screen
  20635. * @param y position on screen
  20636. * @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
  20637. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20638. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20639. */
  20640. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20641. var _this = this;
  20642. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20643. };
  20644. /** Launch a ray to try to pick a sprite in the scene
  20645. * @param x position on screen
  20646. * @param y position on screen
  20647. * @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
  20648. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20649. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20650. */
  20651. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20652. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20653. if (!ray) {
  20654. return null;
  20655. }
  20656. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20657. };
  20658. /** Use the given ray to pick a mesh in the scene
  20659. * @param ray The ray to use to pick meshes
  20660. * @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
  20661. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20662. */
  20663. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20664. var _this = this;
  20665. return this._internalPick(function (world) {
  20666. if (!_this._pickWithRayInverseMatrix) {
  20667. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20668. }
  20669. world.invertToRef(_this._pickWithRayInverseMatrix);
  20670. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20671. }, predicate, fastCheck);
  20672. };
  20673. /**
  20674. * Launch a ray to try to pick a mesh in the scene
  20675. * @param x X position on screen
  20676. * @param y Y position on screen
  20677. * @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
  20678. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20679. */
  20680. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20681. var _this = this;
  20682. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20683. };
  20684. /**
  20685. * Launch a ray to try to pick a mesh in the scene
  20686. * @param ray Ray to use
  20687. * @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
  20688. */
  20689. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20690. var _this = this;
  20691. return this._internalMultiPick(function (world) {
  20692. if (!_this._pickWithRayInverseMatrix) {
  20693. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20694. }
  20695. world.invertToRef(_this._pickWithRayInverseMatrix);
  20696. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20697. }, predicate);
  20698. };
  20699. Scene.prototype.setPointerOverMesh = function (mesh) {
  20700. if (this._pointerOverMesh === mesh) {
  20701. return;
  20702. }
  20703. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20704. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20705. }
  20706. this._pointerOverMesh = mesh;
  20707. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20708. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20709. }
  20710. };
  20711. Scene.prototype.getPointerOverMesh = function () {
  20712. return this._pointerOverMesh;
  20713. };
  20714. Scene.prototype.setPointerOverSprite = function (sprite) {
  20715. if (this._pointerOverSprite === sprite) {
  20716. return;
  20717. }
  20718. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20719. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20720. }
  20721. this._pointerOverSprite = sprite;
  20722. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20723. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20724. }
  20725. };
  20726. Scene.prototype.getPointerOverSprite = function () {
  20727. return this._pointerOverSprite;
  20728. };
  20729. // Physics
  20730. Scene.prototype.getPhysicsEngine = function () {
  20731. return this._physicsEngine;
  20732. };
  20733. /**
  20734. * Enables physics to the current scene
  20735. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20736. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20737. * @return {boolean} was the physics engine initialized
  20738. */
  20739. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20740. if (gravity === void 0) { gravity = null; }
  20741. if (this._physicsEngine) {
  20742. return true;
  20743. }
  20744. try {
  20745. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20746. return true;
  20747. }
  20748. catch (e) {
  20749. BABYLON.Tools.Error(e.message);
  20750. return false;
  20751. }
  20752. };
  20753. Scene.prototype.disablePhysicsEngine = function () {
  20754. if (!this._physicsEngine) {
  20755. return;
  20756. }
  20757. this._physicsEngine.dispose();
  20758. this._physicsEngine = null;
  20759. };
  20760. Scene.prototype.isPhysicsEnabled = function () {
  20761. return this._physicsEngine !== undefined;
  20762. };
  20763. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20764. var mesh = compound.parts[0].mesh;
  20765. if (mesh.physicsImpostor) {
  20766. mesh.physicsImpostor.dispose();
  20767. mesh.physicsImpostor = null;
  20768. }
  20769. };
  20770. // Misc.
  20771. Scene.prototype._rebuildGeometries = function () {
  20772. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20773. var geometry = _a[_i];
  20774. geometry._rebuild();
  20775. }
  20776. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20777. var mesh = _c[_b];
  20778. mesh._rebuild();
  20779. }
  20780. if (this.postProcessManager) {
  20781. this.postProcessManager._rebuild();
  20782. }
  20783. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20784. var layer = _e[_d];
  20785. layer._rebuild();
  20786. }
  20787. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20788. var highlightLayer = _g[_f];
  20789. highlightLayer._rebuild();
  20790. }
  20791. if (this._boundingBoxRenderer) {
  20792. this._boundingBoxRenderer._rebuild();
  20793. }
  20794. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20795. var system = _j[_h];
  20796. system.rebuild();
  20797. }
  20798. if (this._postProcessRenderPipelineManager) {
  20799. this._postProcessRenderPipelineManager._rebuild();
  20800. }
  20801. };
  20802. Scene.prototype._rebuildTextures = function () {
  20803. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20804. var texture = _a[_i];
  20805. texture._rebuild();
  20806. }
  20807. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20808. };
  20809. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20810. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20811. if (replace === void 0) { replace = false; }
  20812. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20813. // Dispose existing camera or light in replace mode.
  20814. if (replace) {
  20815. if (this.activeCamera) {
  20816. this.activeCamera.dispose();
  20817. this.activeCamera = null;
  20818. }
  20819. if (this.lights) {
  20820. for (var i = 0; i < this.lights.length; i++) {
  20821. this.lights[i].dispose();
  20822. }
  20823. }
  20824. }
  20825. // Light
  20826. if (this.lights.length === 0) {
  20827. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20828. }
  20829. // Camera
  20830. if (!this.activeCamera) {
  20831. var worldExtends = this.getWorldExtends();
  20832. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20833. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20834. var camera;
  20835. var radius = worldSize.length() * 1.5;
  20836. if (createArcRotateCamera) {
  20837. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20838. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20839. arcRotateCamera.wheelPrecision = 100 / radius;
  20840. camera = arcRotateCamera;
  20841. }
  20842. else {
  20843. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20844. freeCamera.setTarget(worldCenter);
  20845. camera = freeCamera;
  20846. }
  20847. camera.minZ = radius * 0.01;
  20848. camera.maxZ = radius * 100;
  20849. camera.speed = radius * 0.2;
  20850. this.activeCamera = camera;
  20851. var canvas = this.getEngine().getRenderingCanvas();
  20852. if (attachCameraControls && canvas) {
  20853. camera.attachControl(canvas);
  20854. }
  20855. }
  20856. };
  20857. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20858. if (pbr === void 0) { pbr = false; }
  20859. if (scale === void 0) { scale = 1000; }
  20860. if (blur === void 0) { blur = 0; }
  20861. if (environmentTexture) {
  20862. this.environmentTexture = environmentTexture;
  20863. }
  20864. if (!this.environmentTexture) {
  20865. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20866. return null;
  20867. }
  20868. // Skybox
  20869. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20870. if (pbr) {
  20871. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20872. hdrSkyboxMaterial.backFaceCulling = false;
  20873. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20874. if (hdrSkyboxMaterial.reflectionTexture) {
  20875. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20876. }
  20877. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20878. hdrSkyboxMaterial.disableLighting = true;
  20879. hdrSkyboxMaterial.twoSidedLighting = true;
  20880. hdrSkybox.infiniteDistance = true;
  20881. hdrSkybox.material = hdrSkyboxMaterial;
  20882. }
  20883. else {
  20884. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20885. skyboxMaterial.backFaceCulling = false;
  20886. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20887. if (skyboxMaterial.reflectionTexture) {
  20888. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20889. }
  20890. skyboxMaterial.disableLighting = true;
  20891. hdrSkybox.infiniteDistance = true;
  20892. hdrSkybox.material = skyboxMaterial;
  20893. }
  20894. return hdrSkybox;
  20895. };
  20896. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20897. if (webVROptions === void 0) { webVROptions = {}; }
  20898. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20899. };
  20900. // Tags
  20901. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20902. if (tagsQuery === undefined) {
  20903. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20904. return list;
  20905. }
  20906. var listByTags = [];
  20907. forEach = forEach || (function (item) { return; });
  20908. for (var i in list) {
  20909. var item = list[i];
  20910. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20911. listByTags.push(item);
  20912. forEach(item);
  20913. }
  20914. }
  20915. return listByTags;
  20916. };
  20917. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20918. return this._getByTags(this.meshes, tagsQuery, forEach);
  20919. };
  20920. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20921. return this._getByTags(this.cameras, tagsQuery, forEach);
  20922. };
  20923. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20924. return this._getByTags(this.lights, tagsQuery, forEach);
  20925. };
  20926. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20927. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20928. };
  20929. /**
  20930. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20931. * This allowed control for front to back rendering or reversly depending of the special needs.
  20932. *
  20933. * @param renderingGroupId The rendering group id corresponding to its index
  20934. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20935. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20936. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20937. */
  20938. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20939. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20940. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20941. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20942. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20943. };
  20944. /**
  20945. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20946. *
  20947. * @param renderingGroupId The rendering group id corresponding to its index
  20948. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20949. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20950. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20951. */
  20952. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20953. if (depth === void 0) { depth = true; }
  20954. if (stencil === void 0) { stencil = true; }
  20955. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20956. };
  20957. /**
  20958. * Will flag all materials as dirty to trigger new shader compilation
  20959. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20960. */
  20961. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20962. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20963. var material = _a[_i];
  20964. if (predicate && !predicate(material)) {
  20965. continue;
  20966. }
  20967. material.markAsDirty(flag);
  20968. }
  20969. };
  20970. // Statics
  20971. Scene._FOGMODE_NONE = 0;
  20972. Scene._FOGMODE_EXP = 1;
  20973. Scene._FOGMODE_EXP2 = 2;
  20974. Scene._FOGMODE_LINEAR = 3;
  20975. Scene._uniqueIdCounter = 0;
  20976. Scene.MinDeltaTime = 1.0;
  20977. Scene.MaxDeltaTime = 1000.0;
  20978. /** The distance in pixel that you have to move to prevent some events */
  20979. Scene.DragMovementThreshold = 10; // in pixels
  20980. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20981. Scene.LongPressDelay = 500; // in milliseconds
  20982. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20983. Scene.DoubleClickDelay = 300; // in milliseconds
  20984. /** If you need to check double click without raising a single click at first click, enable this flag */
  20985. Scene.ExclusiveDoubleClickMode = false;
  20986. return Scene;
  20987. }());
  20988. BABYLON.Scene = Scene;
  20989. })(BABYLON || (BABYLON = {}));
  20990. //# sourceMappingURL=babylon.scene.js.map
  20991. var BABYLON;
  20992. (function (BABYLON) {
  20993. var Buffer = /** @class */ (function () {
  20994. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20995. if (instanced === void 0) { instanced = false; }
  20996. if (engine instanceof BABYLON.Mesh) {
  20997. this._engine = engine.getScene().getEngine();
  20998. }
  20999. else {
  21000. this._engine = engine;
  21001. }
  21002. this._updatable = updatable;
  21003. this._data = data;
  21004. this._strideSize = stride;
  21005. if (!postponeInternalCreation) {
  21006. this.create();
  21007. }
  21008. this._instanced = instanced;
  21009. this._instanceDivisor = instanced ? 1 : 0;
  21010. }
  21011. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21012. // a lot of these parameters are ignored as they are overriden by the buffer
  21013. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21014. };
  21015. // Properties
  21016. Buffer.prototype.isUpdatable = function () {
  21017. return this._updatable;
  21018. };
  21019. Buffer.prototype.getData = function () {
  21020. return this._data;
  21021. };
  21022. Buffer.prototype.getBuffer = function () {
  21023. return this._buffer;
  21024. };
  21025. Buffer.prototype.getStrideSize = function () {
  21026. return this._strideSize;
  21027. };
  21028. Buffer.prototype.getIsInstanced = function () {
  21029. return this._instanced;
  21030. };
  21031. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21032. get: function () {
  21033. return this._instanceDivisor;
  21034. },
  21035. set: function (value) {
  21036. this._instanceDivisor = value;
  21037. if (value == 0) {
  21038. this._instanced = false;
  21039. }
  21040. else {
  21041. this._instanced = true;
  21042. }
  21043. },
  21044. enumerable: true,
  21045. configurable: true
  21046. });
  21047. // Methods
  21048. Buffer.prototype.create = function (data) {
  21049. if (data === void 0) { data = null; }
  21050. if (!data && this._buffer) {
  21051. return; // nothing to do
  21052. }
  21053. data = data || this._data;
  21054. if (!data) {
  21055. return;
  21056. }
  21057. if (!this._buffer) {
  21058. if (this._updatable) {
  21059. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21060. this._data = data;
  21061. }
  21062. else {
  21063. this._buffer = this._engine.createVertexBuffer(data);
  21064. }
  21065. }
  21066. else if (this._updatable) {
  21067. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21068. this._data = data;
  21069. }
  21070. };
  21071. Buffer.prototype._rebuild = function () {
  21072. this._buffer = null;
  21073. this.create(this._data);
  21074. };
  21075. Buffer.prototype.update = function (data) {
  21076. this.create(data);
  21077. };
  21078. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21079. if (!this._buffer) {
  21080. return;
  21081. }
  21082. if (this._updatable) {
  21083. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21084. this._data = null;
  21085. }
  21086. };
  21087. Buffer.prototype.dispose = function () {
  21088. if (!this._buffer) {
  21089. return;
  21090. }
  21091. if (this._engine._releaseBuffer(this._buffer)) {
  21092. this._buffer = null;
  21093. }
  21094. };
  21095. return Buffer;
  21096. }());
  21097. BABYLON.Buffer = Buffer;
  21098. })(BABYLON || (BABYLON = {}));
  21099. //# sourceMappingURL=babylon.buffer.js.map
  21100. var BABYLON;
  21101. (function (BABYLON) {
  21102. var VertexBuffer = /** @class */ (function () {
  21103. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21104. if (!stride) {
  21105. // Deduce stride from kind
  21106. switch (kind) {
  21107. case VertexBuffer.PositionKind:
  21108. stride = 3;
  21109. break;
  21110. case VertexBuffer.NormalKind:
  21111. stride = 3;
  21112. break;
  21113. case VertexBuffer.UVKind:
  21114. case VertexBuffer.UV2Kind:
  21115. case VertexBuffer.UV3Kind:
  21116. case VertexBuffer.UV4Kind:
  21117. case VertexBuffer.UV5Kind:
  21118. case VertexBuffer.UV6Kind:
  21119. stride = 2;
  21120. break;
  21121. case VertexBuffer.TangentKind:
  21122. case VertexBuffer.ColorKind:
  21123. stride = 4;
  21124. break;
  21125. case VertexBuffer.MatricesIndicesKind:
  21126. case VertexBuffer.MatricesIndicesExtraKind:
  21127. stride = 4;
  21128. break;
  21129. case VertexBuffer.MatricesWeightsKind:
  21130. case VertexBuffer.MatricesWeightsExtraKind:
  21131. default:
  21132. stride = 4;
  21133. break;
  21134. }
  21135. }
  21136. if (data instanceof BABYLON.Buffer) {
  21137. if (!stride) {
  21138. stride = data.getStrideSize();
  21139. }
  21140. this._buffer = data;
  21141. this._ownsBuffer = false;
  21142. }
  21143. else {
  21144. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21145. this._ownsBuffer = true;
  21146. }
  21147. this._stride = stride;
  21148. this._offset = offset ? offset : 0;
  21149. this._size = size ? size : stride;
  21150. this._kind = kind;
  21151. }
  21152. VertexBuffer.prototype._rebuild = function () {
  21153. if (!this._buffer) {
  21154. return;
  21155. }
  21156. this._buffer._rebuild();
  21157. };
  21158. /**
  21159. * Returns the kind of the VertexBuffer (string).
  21160. */
  21161. VertexBuffer.prototype.getKind = function () {
  21162. return this._kind;
  21163. };
  21164. // Properties
  21165. /**
  21166. * Boolean : is the VertexBuffer updatable ?
  21167. */
  21168. VertexBuffer.prototype.isUpdatable = function () {
  21169. return this._buffer.isUpdatable();
  21170. };
  21171. /**
  21172. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21173. */
  21174. VertexBuffer.prototype.getData = function () {
  21175. return this._buffer.getData();
  21176. };
  21177. /**
  21178. * Returns the WebGLBuffer associated to the VertexBuffer.
  21179. */
  21180. VertexBuffer.prototype.getBuffer = function () {
  21181. return this._buffer.getBuffer();
  21182. };
  21183. /**
  21184. * Returns the stride of the VertexBuffer (integer).
  21185. */
  21186. VertexBuffer.prototype.getStrideSize = function () {
  21187. return this._stride;
  21188. };
  21189. /**
  21190. * Returns the offset (integer).
  21191. */
  21192. VertexBuffer.prototype.getOffset = function () {
  21193. return this._offset;
  21194. };
  21195. /**
  21196. * Returns the VertexBuffer total size (integer).
  21197. */
  21198. VertexBuffer.prototype.getSize = function () {
  21199. return this._size;
  21200. };
  21201. /**
  21202. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21203. */
  21204. VertexBuffer.prototype.getIsInstanced = function () {
  21205. return this._buffer.getIsInstanced();
  21206. };
  21207. /**
  21208. * Returns the instancing divisor, zero for non-instanced (integer).
  21209. */
  21210. VertexBuffer.prototype.getInstanceDivisor = function () {
  21211. return this._buffer.instanceDivisor;
  21212. };
  21213. // Methods
  21214. /**
  21215. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21216. * Returns the created WebGLBuffer.
  21217. */
  21218. VertexBuffer.prototype.create = function (data) {
  21219. return this._buffer.create(data);
  21220. };
  21221. /**
  21222. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21223. * Returns the updated WebGLBuffer.
  21224. */
  21225. VertexBuffer.prototype.update = function (data) {
  21226. return this._buffer.update(data);
  21227. };
  21228. /**
  21229. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21230. * Returns the directly updated WebGLBuffer.
  21231. */
  21232. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21233. return this._buffer.updateDirectly(data, offset);
  21234. };
  21235. /**
  21236. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21237. */
  21238. VertexBuffer.prototype.dispose = function () {
  21239. if (this._ownsBuffer) {
  21240. this._buffer.dispose();
  21241. }
  21242. };
  21243. Object.defineProperty(VertexBuffer, "PositionKind", {
  21244. get: function () {
  21245. return VertexBuffer._PositionKind;
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. Object.defineProperty(VertexBuffer, "NormalKind", {
  21251. get: function () {
  21252. return VertexBuffer._NormalKind;
  21253. },
  21254. enumerable: true,
  21255. configurable: true
  21256. });
  21257. Object.defineProperty(VertexBuffer, "TangentKind", {
  21258. get: function () {
  21259. return VertexBuffer._TangentKind;
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. Object.defineProperty(VertexBuffer, "UVKind", {
  21265. get: function () {
  21266. return VertexBuffer._UVKind;
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21272. get: function () {
  21273. return VertexBuffer._UV2Kind;
  21274. },
  21275. enumerable: true,
  21276. configurable: true
  21277. });
  21278. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21279. get: function () {
  21280. return VertexBuffer._UV3Kind;
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21286. get: function () {
  21287. return VertexBuffer._UV4Kind;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21293. get: function () {
  21294. return VertexBuffer._UV5Kind;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21300. get: function () {
  21301. return VertexBuffer._UV6Kind;
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(VertexBuffer, "ColorKind", {
  21307. get: function () {
  21308. return VertexBuffer._ColorKind;
  21309. },
  21310. enumerable: true,
  21311. configurable: true
  21312. });
  21313. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21314. get: function () {
  21315. return VertexBuffer._MatricesIndicesKind;
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21321. get: function () {
  21322. return VertexBuffer._MatricesWeightsKind;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21328. get: function () {
  21329. return VertexBuffer._MatricesIndicesExtraKind;
  21330. },
  21331. enumerable: true,
  21332. configurable: true
  21333. });
  21334. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21335. get: function () {
  21336. return VertexBuffer._MatricesWeightsExtraKind;
  21337. },
  21338. enumerable: true,
  21339. configurable: true
  21340. });
  21341. // Enums
  21342. VertexBuffer._PositionKind = "position";
  21343. VertexBuffer._NormalKind = "normal";
  21344. VertexBuffer._TangentKind = "tangent";
  21345. VertexBuffer._UVKind = "uv";
  21346. VertexBuffer._UV2Kind = "uv2";
  21347. VertexBuffer._UV3Kind = "uv3";
  21348. VertexBuffer._UV4Kind = "uv4";
  21349. VertexBuffer._UV5Kind = "uv5";
  21350. VertexBuffer._UV6Kind = "uv6";
  21351. VertexBuffer._ColorKind = "color";
  21352. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21353. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21354. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21355. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21356. return VertexBuffer;
  21357. }());
  21358. BABYLON.VertexBuffer = VertexBuffer;
  21359. })(BABYLON || (BABYLON = {}));
  21360. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21361. var BABYLON;
  21362. (function (BABYLON) {
  21363. var InternalTexture = /** @class */ (function () {
  21364. function InternalTexture(engine, dataSource) {
  21365. this.onLoadedObservable = new BABYLON.Observable();
  21366. // Private
  21367. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21368. this._references = 1;
  21369. this._engine = engine;
  21370. this._dataSource = dataSource;
  21371. this._webGLTexture = engine._createTexture();
  21372. }
  21373. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21374. get: function () {
  21375. return this._dataSource;
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. InternalTexture.prototype.incrementReferences = function () {
  21381. this._references++;
  21382. };
  21383. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21384. if (depth === void 0) { depth = 1; }
  21385. this.width = width;
  21386. this.height = height;
  21387. this.depth = depth;
  21388. this.baseWidth = width;
  21389. this.baseHeight = height;
  21390. this.baseDepth = depth;
  21391. this._size = width * height * depth;
  21392. };
  21393. InternalTexture.prototype._rebuild = function () {
  21394. var _this = this;
  21395. var proxy;
  21396. this.isReady = false;
  21397. this._cachedCoordinatesMode = null;
  21398. this._cachedWrapU = null;
  21399. this._cachedWrapV = null;
  21400. this._cachedAnisotropicFilteringLevel = null;
  21401. switch (this._dataSource) {
  21402. case InternalTexture.DATASOURCE_TEMP:
  21403. return;
  21404. case InternalTexture.DATASOURCE_URL:
  21405. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21406. _this.isReady = true;
  21407. }, null, this._buffer, undefined, this.format);
  21408. proxy._swapAndDie(this);
  21409. return;
  21410. case InternalTexture.DATASOURCE_RAW:
  21411. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21412. proxy._swapAndDie(this);
  21413. this.isReady = true;
  21414. return;
  21415. case InternalTexture.DATASOURCE_RAW3D:
  21416. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21417. proxy._swapAndDie(this);
  21418. this.isReady = true;
  21419. return;
  21420. case InternalTexture.DATASOURCE_DYNAMIC:
  21421. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21422. proxy._swapAndDie(this);
  21423. // The engine will make sure to update content so no need to flag it as isReady = true
  21424. return;
  21425. case InternalTexture.DATASOURCE_RENDERTARGET:
  21426. var options = new BABYLON.RenderTargetCreationOptions();
  21427. options.generateDepthBuffer = this._generateDepthBuffer;
  21428. options.generateMipMaps = this.generateMipMaps;
  21429. options.generateStencilBuffer = this._generateStencilBuffer;
  21430. options.samplingMode = this.samplingMode;
  21431. options.type = this.type;
  21432. if (this.isCube) {
  21433. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21434. }
  21435. else {
  21436. var size = {
  21437. width: this.width,
  21438. height: this.height
  21439. };
  21440. proxy = this._engine.createRenderTargetTexture(size, options);
  21441. }
  21442. proxy._swapAndDie(this);
  21443. this.isReady = true;
  21444. return;
  21445. case InternalTexture.DATASOURCE_CUBE:
  21446. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21447. _this.isReady = true;
  21448. }, null, this.format, this._extension);
  21449. proxy._swapAndDie(this);
  21450. return;
  21451. case InternalTexture.DATASOURCE_CUBERAW:
  21452. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21453. proxy._swapAndDie(this);
  21454. this.isReady = true;
  21455. return;
  21456. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21457. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21458. if (proxy) {
  21459. proxy._swapAndDie(_this);
  21460. }
  21461. _this.isReady = true;
  21462. }, null, this.format, this._extension);
  21463. return;
  21464. }
  21465. };
  21466. InternalTexture.prototype._swapAndDie = function (target) {
  21467. target._webGLTexture = this._webGLTexture;
  21468. if (this._framebuffer) {
  21469. target._framebuffer = this._framebuffer;
  21470. }
  21471. if (this._depthStencilBuffer) {
  21472. target._depthStencilBuffer = this._depthStencilBuffer;
  21473. }
  21474. if (this._lodTextureHigh) {
  21475. if (target._lodTextureHigh) {
  21476. target._lodTextureHigh.dispose();
  21477. }
  21478. target._lodTextureHigh = this._lodTextureHigh;
  21479. }
  21480. if (this._lodTextureMid) {
  21481. if (target._lodTextureMid) {
  21482. target._lodTextureMid.dispose();
  21483. }
  21484. target._lodTextureMid = this._lodTextureMid;
  21485. }
  21486. if (this._lodTextureLow) {
  21487. if (target._lodTextureLow) {
  21488. target._lodTextureLow.dispose();
  21489. }
  21490. target._lodTextureLow = this._lodTextureLow;
  21491. }
  21492. var cache = this._engine.getLoadedTexturesCache();
  21493. var index = cache.indexOf(this);
  21494. if (index !== -1) {
  21495. cache.splice(index, 1);
  21496. }
  21497. };
  21498. InternalTexture.prototype.dispose = function () {
  21499. if (!this._webGLTexture) {
  21500. return;
  21501. }
  21502. this._references--;
  21503. if (this._references === 0) {
  21504. this._engine._releaseTexture(this);
  21505. this._webGLTexture = null;
  21506. }
  21507. };
  21508. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21509. InternalTexture.DATASOURCE_URL = 1;
  21510. InternalTexture.DATASOURCE_TEMP = 2;
  21511. InternalTexture.DATASOURCE_RAW = 3;
  21512. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21513. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21514. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21515. InternalTexture.DATASOURCE_CUBE = 7;
  21516. InternalTexture.DATASOURCE_CUBERAW = 8;
  21517. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21518. InternalTexture.DATASOURCE_RAW3D = 10;
  21519. return InternalTexture;
  21520. }());
  21521. BABYLON.InternalTexture = InternalTexture;
  21522. })(BABYLON || (BABYLON = {}));
  21523. //# sourceMappingURL=babylon.internalTexture.js.map
  21524. var BABYLON;
  21525. (function (BABYLON) {
  21526. var BaseTexture = /** @class */ (function () {
  21527. function BaseTexture(scene) {
  21528. this._hasAlpha = false;
  21529. this.getAlphaFromRGB = false;
  21530. this.level = 1;
  21531. this.coordinatesIndex = 0;
  21532. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21533. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21534. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21535. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21536. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21537. this.isCube = false;
  21538. this.is3D = false;
  21539. this.gammaSpace = true;
  21540. this.invertZ = false;
  21541. this.lodLevelInAlpha = false;
  21542. this.lodGenerationOffset = 0.0;
  21543. this.lodGenerationScale = 0.8;
  21544. this.isRenderTarget = false;
  21545. this.animations = new Array();
  21546. /**
  21547. * An event triggered when the texture is disposed.
  21548. * @type {BABYLON.Observable}
  21549. */
  21550. this.onDisposeObservable = new BABYLON.Observable();
  21551. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21552. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21553. if (this._scene) {
  21554. this._scene.textures.push(this);
  21555. }
  21556. this._uid = null;
  21557. }
  21558. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21559. get: function () {
  21560. return this._hasAlpha;
  21561. },
  21562. set: function (value) {
  21563. if (this._hasAlpha === value) {
  21564. return;
  21565. }
  21566. this._hasAlpha = 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, "coordinatesMode", {
  21575. get: function () {
  21576. return this._coordinatesMode;
  21577. },
  21578. set: function (value) {
  21579. if (this._coordinatesMode === value) {
  21580. return;
  21581. }
  21582. this._coordinatesMode = value;
  21583. if (this._scene) {
  21584. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21585. }
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(BaseTexture.prototype, "uid", {
  21591. get: function () {
  21592. if (!this._uid) {
  21593. this._uid = BABYLON.Tools.RandomId();
  21594. }
  21595. return this._uid;
  21596. },
  21597. enumerable: true,
  21598. configurable: true
  21599. });
  21600. BaseTexture.prototype.toString = function () {
  21601. return this.name;
  21602. };
  21603. BaseTexture.prototype.getClassName = function () {
  21604. return "BaseTexture";
  21605. };
  21606. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21607. set: function (callback) {
  21608. if (this._onDisposeObserver) {
  21609. this.onDisposeObservable.remove(this._onDisposeObserver);
  21610. }
  21611. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21617. get: function () {
  21618. return true;
  21619. },
  21620. enumerable: true,
  21621. configurable: true
  21622. });
  21623. BaseTexture.prototype.getScene = function () {
  21624. return this._scene;
  21625. };
  21626. BaseTexture.prototype.getTextureMatrix = function () {
  21627. return BABYLON.Matrix.IdentityReadOnly;
  21628. };
  21629. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21630. return BABYLON.Matrix.IdentityReadOnly;
  21631. };
  21632. BaseTexture.prototype.getInternalTexture = function () {
  21633. return this._texture;
  21634. };
  21635. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21636. return !this.isBlocking || this.isReady();
  21637. };
  21638. BaseTexture.prototype.isReady = function () {
  21639. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21640. this.delayLoad();
  21641. return false;
  21642. }
  21643. if (this._texture) {
  21644. return this._texture.isReady;
  21645. }
  21646. return false;
  21647. };
  21648. BaseTexture.prototype.getSize = function () {
  21649. if (this._texture && this._texture.width) {
  21650. return new BABYLON.Size(this._texture.width, this._texture.height);
  21651. }
  21652. if (this._texture && this._texture._size) {
  21653. return new BABYLON.Size(this._texture._size, this._texture._size);
  21654. }
  21655. return BABYLON.Size.Zero();
  21656. };
  21657. BaseTexture.prototype.getBaseSize = function () {
  21658. if (!this.isReady() || !this._texture)
  21659. return BABYLON.Size.Zero();
  21660. if (this._texture._size) {
  21661. return new BABYLON.Size(this._texture._size, this._texture._size);
  21662. }
  21663. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21664. };
  21665. BaseTexture.prototype.scale = function (ratio) {
  21666. };
  21667. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21668. get: function () {
  21669. return false;
  21670. },
  21671. enumerable: true,
  21672. configurable: true
  21673. });
  21674. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21675. if (!this._scene) {
  21676. return null;
  21677. }
  21678. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21679. for (var index = 0; index < texturesCache.length; index++) {
  21680. var texturesCacheEntry = texturesCache[index];
  21681. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21682. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21683. texturesCacheEntry.incrementReferences();
  21684. return texturesCacheEntry;
  21685. }
  21686. }
  21687. }
  21688. return null;
  21689. };
  21690. BaseTexture.prototype._rebuild = function () {
  21691. };
  21692. BaseTexture.prototype.delayLoad = function () {
  21693. };
  21694. BaseTexture.prototype.clone = function () {
  21695. return null;
  21696. };
  21697. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21698. get: function () {
  21699. if (!this._texture) {
  21700. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21701. }
  21702. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21708. get: function () {
  21709. if (!this._texture) {
  21710. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21711. }
  21712. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. BaseTexture.prototype.readPixels = function (faceIndex) {
  21718. if (faceIndex === void 0) { faceIndex = 0; }
  21719. if (!this._texture) {
  21720. return null;
  21721. }
  21722. var size = this.getSize();
  21723. var scene = this.getScene();
  21724. if (!scene) {
  21725. return null;
  21726. }
  21727. var engine = scene.getEngine();
  21728. if (this._texture.isCube) {
  21729. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21730. }
  21731. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21732. };
  21733. BaseTexture.prototype.releaseInternalTexture = function () {
  21734. if (this._texture) {
  21735. this._texture.dispose();
  21736. this._texture = null;
  21737. }
  21738. };
  21739. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21740. get: function () {
  21741. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21742. return null;
  21743. }
  21744. if (!this._texture._sphericalPolynomial) {
  21745. this._texture._sphericalPolynomial =
  21746. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21747. }
  21748. return this._texture._sphericalPolynomial;
  21749. },
  21750. set: function (value) {
  21751. if (this._texture) {
  21752. this._texture._sphericalPolynomial = value;
  21753. }
  21754. },
  21755. enumerable: true,
  21756. configurable: true
  21757. });
  21758. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21759. get: function () {
  21760. if (this._texture) {
  21761. return this._texture._lodTextureHigh;
  21762. }
  21763. return null;
  21764. },
  21765. enumerable: true,
  21766. configurable: true
  21767. });
  21768. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21769. get: function () {
  21770. if (this._texture) {
  21771. return this._texture._lodTextureMid;
  21772. }
  21773. return null;
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21779. get: function () {
  21780. if (this._texture) {
  21781. return this._texture._lodTextureLow;
  21782. }
  21783. return null;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. BaseTexture.prototype.dispose = function () {
  21789. if (!this._scene) {
  21790. return;
  21791. }
  21792. // Animations
  21793. this._scene.stopAnimation(this);
  21794. // Remove from scene
  21795. this._scene._removePendingData(this);
  21796. var index = this._scene.textures.indexOf(this);
  21797. if (index >= 0) {
  21798. this._scene.textures.splice(index, 1);
  21799. }
  21800. if (this._texture === undefined) {
  21801. return;
  21802. }
  21803. // Release
  21804. this.releaseInternalTexture();
  21805. // Callback
  21806. this.onDisposeObservable.notifyObservers(this);
  21807. this.onDisposeObservable.clear();
  21808. };
  21809. BaseTexture.prototype.serialize = function () {
  21810. if (!this.name) {
  21811. return null;
  21812. }
  21813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21814. // Animations
  21815. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21816. return serializationObject;
  21817. };
  21818. BaseTexture.WhenAllReady = function (textures, callback) {
  21819. var numRemaining = textures.length;
  21820. if (numRemaining === 0) {
  21821. callback();
  21822. return;
  21823. }
  21824. var _loop_1 = function () {
  21825. texture = textures[i];
  21826. if (texture.isReady()) {
  21827. if (--numRemaining === 0) {
  21828. callback();
  21829. }
  21830. }
  21831. else {
  21832. onLoadObservable = texture.onLoadObservable;
  21833. var onLoadCallback_1 = function () {
  21834. onLoadObservable.removeCallback(onLoadCallback_1);
  21835. if (--numRemaining === 0) {
  21836. callback();
  21837. }
  21838. };
  21839. onLoadObservable.add(onLoadCallback_1);
  21840. }
  21841. };
  21842. var texture, onLoadObservable;
  21843. for (var i = 0; i < textures.length; i++) {
  21844. _loop_1();
  21845. }
  21846. };
  21847. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21848. __decorate([
  21849. BABYLON.serialize()
  21850. ], BaseTexture.prototype, "name", void 0);
  21851. __decorate([
  21852. BABYLON.serialize("hasAlpha")
  21853. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21854. __decorate([
  21855. BABYLON.serialize()
  21856. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21857. __decorate([
  21858. BABYLON.serialize()
  21859. ], BaseTexture.prototype, "level", void 0);
  21860. __decorate([
  21861. BABYLON.serialize()
  21862. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21863. __decorate([
  21864. BABYLON.serialize("coordinatesMode")
  21865. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21866. __decorate([
  21867. BABYLON.serialize()
  21868. ], BaseTexture.prototype, "wrapU", void 0);
  21869. __decorate([
  21870. BABYLON.serialize()
  21871. ], BaseTexture.prototype, "wrapV", void 0);
  21872. __decorate([
  21873. BABYLON.serialize()
  21874. ], BaseTexture.prototype, "wrapR", void 0);
  21875. __decorate([
  21876. BABYLON.serialize()
  21877. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21878. __decorate([
  21879. BABYLON.serialize()
  21880. ], BaseTexture.prototype, "isCube", void 0);
  21881. __decorate([
  21882. BABYLON.serialize()
  21883. ], BaseTexture.prototype, "is3D", void 0);
  21884. __decorate([
  21885. BABYLON.serialize()
  21886. ], BaseTexture.prototype, "gammaSpace", void 0);
  21887. __decorate([
  21888. BABYLON.serialize()
  21889. ], BaseTexture.prototype, "invertZ", void 0);
  21890. __decorate([
  21891. BABYLON.serialize()
  21892. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21893. __decorate([
  21894. BABYLON.serialize()
  21895. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21896. __decorate([
  21897. BABYLON.serialize()
  21898. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21899. __decorate([
  21900. BABYLON.serialize()
  21901. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21902. return BaseTexture;
  21903. }());
  21904. BABYLON.BaseTexture = BaseTexture;
  21905. })(BABYLON || (BABYLON = {}));
  21906. //# sourceMappingURL=babylon.baseTexture.js.map
  21907. var BABYLON;
  21908. (function (BABYLON) {
  21909. var Texture = /** @class */ (function (_super) {
  21910. __extends(Texture, _super);
  21911. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21912. if (noMipmap === void 0) { noMipmap = false; }
  21913. if (invertY === void 0) { invertY = true; }
  21914. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21915. if (onLoad === void 0) { onLoad = null; }
  21916. if (onError === void 0) { onError = null; }
  21917. if (buffer === void 0) { buffer = null; }
  21918. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21919. var _this = _super.call(this, scene) || this;
  21920. _this.uOffset = 0;
  21921. _this.vOffset = 0;
  21922. _this.uScale = 1.0;
  21923. _this.vScale = 1.0;
  21924. _this.uAng = 0;
  21925. _this.vAng = 0;
  21926. _this.wAng = 0;
  21927. _this._isBlocking = true;
  21928. _this.name = url || "";
  21929. _this.url = url;
  21930. _this._noMipmap = noMipmap;
  21931. _this._invertY = invertY;
  21932. _this._samplingMode = samplingMode;
  21933. _this._buffer = buffer;
  21934. _this._deleteBuffer = deleteBuffer;
  21935. if (format) {
  21936. _this._format = format;
  21937. }
  21938. scene = _this.getScene();
  21939. if (!scene) {
  21940. return _this;
  21941. }
  21942. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21943. var load = function () {
  21944. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21945. _this.onLoadObservable.notifyObservers(_this);
  21946. }
  21947. if (onLoad) {
  21948. onLoad();
  21949. }
  21950. if (!_this.isBlocking && scene) {
  21951. scene.resetCachedMaterial();
  21952. }
  21953. };
  21954. if (!_this.url) {
  21955. _this._delayedOnLoad = load;
  21956. _this._delayedOnError = onError;
  21957. return _this;
  21958. }
  21959. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21960. if (!_this._texture) {
  21961. if (!scene.useDelayedTextureLoading) {
  21962. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21963. if (deleteBuffer) {
  21964. delete _this._buffer;
  21965. }
  21966. }
  21967. else {
  21968. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21969. _this._delayedOnLoad = load;
  21970. _this._delayedOnError = onError;
  21971. }
  21972. }
  21973. else {
  21974. if (_this._texture.isReady) {
  21975. BABYLON.Tools.SetImmediate(function () { return load(); });
  21976. }
  21977. else {
  21978. _this._texture.onLoadedObservable.add(load);
  21979. }
  21980. }
  21981. return _this;
  21982. }
  21983. Object.defineProperty(Texture.prototype, "noMipmap", {
  21984. get: function () {
  21985. return this._noMipmap;
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Texture.prototype, "isBlocking", {
  21991. get: function () {
  21992. return this._isBlocking;
  21993. },
  21994. set: function (value) {
  21995. this._isBlocking = value;
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(Texture.prototype, "samplingMode", {
  22001. get: function () {
  22002. return this._samplingMode;
  22003. },
  22004. enumerable: true,
  22005. configurable: true
  22006. });
  22007. Texture.prototype.updateURL = function (url) {
  22008. this.url = url;
  22009. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22010. this.delayLoad();
  22011. };
  22012. Texture.prototype.delayLoad = function () {
  22013. var _this = this;
  22014. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22015. return;
  22016. }
  22017. var scene = this.getScene();
  22018. if (!scene) {
  22019. return;
  22020. }
  22021. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22022. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22023. if (!this._texture) {
  22024. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22025. if (this._deleteBuffer) {
  22026. delete this._buffer;
  22027. }
  22028. }
  22029. else {
  22030. if (this._texture.isReady) {
  22031. BABYLON.Tools.SetImmediate(function () {
  22032. if (!_this._delayedOnLoad) {
  22033. return;
  22034. }
  22035. _this._delayedOnLoad();
  22036. });
  22037. }
  22038. else {
  22039. if (this._delayedOnLoad) {
  22040. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22041. }
  22042. }
  22043. }
  22044. };
  22045. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22046. if (!this._texture) {
  22047. return;
  22048. }
  22049. var scene = this.getScene();
  22050. if (!scene) {
  22051. return;
  22052. }
  22053. this._samplingMode = samplingMode;
  22054. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22055. };
  22056. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22057. x *= this.uScale;
  22058. y *= this.vScale;
  22059. x -= 0.5 * this.uScale;
  22060. y -= 0.5 * this.vScale;
  22061. z -= 0.5;
  22062. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22063. t.x += 0.5 * this.uScale + this.uOffset;
  22064. t.y += 0.5 * this.vScale + this.vOffset;
  22065. t.z += 0.5;
  22066. };
  22067. Texture.prototype.getTextureMatrix = function () {
  22068. var _this = this;
  22069. if (this.uOffset === this._cachedUOffset &&
  22070. this.vOffset === this._cachedVOffset &&
  22071. this.uScale === this._cachedUScale &&
  22072. this.vScale === this._cachedVScale &&
  22073. this.uAng === this._cachedUAng &&
  22074. this.vAng === this._cachedVAng &&
  22075. this.wAng === this._cachedWAng) {
  22076. return this._cachedTextureMatrix;
  22077. }
  22078. this._cachedUOffset = this.uOffset;
  22079. this._cachedVOffset = this.vOffset;
  22080. this._cachedUScale = this.uScale;
  22081. this._cachedVScale = this.vScale;
  22082. this._cachedUAng = this.uAng;
  22083. this._cachedVAng = this.vAng;
  22084. this._cachedWAng = this.wAng;
  22085. if (!this._cachedTextureMatrix) {
  22086. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22087. this._rowGenerationMatrix = new BABYLON.Matrix();
  22088. this._t0 = BABYLON.Vector3.Zero();
  22089. this._t1 = BABYLON.Vector3.Zero();
  22090. this._t2 = BABYLON.Vector3.Zero();
  22091. }
  22092. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22093. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22094. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22095. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22096. this._t1.subtractInPlace(this._t0);
  22097. this._t2.subtractInPlace(this._t0);
  22098. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22099. this._cachedTextureMatrix.m[0] = this._t1.x;
  22100. this._cachedTextureMatrix.m[1] = this._t1.y;
  22101. this._cachedTextureMatrix.m[2] = this._t1.z;
  22102. this._cachedTextureMatrix.m[4] = this._t2.x;
  22103. this._cachedTextureMatrix.m[5] = this._t2.y;
  22104. this._cachedTextureMatrix.m[6] = this._t2.z;
  22105. this._cachedTextureMatrix.m[8] = this._t0.x;
  22106. this._cachedTextureMatrix.m[9] = this._t0.y;
  22107. this._cachedTextureMatrix.m[10] = this._t0.z;
  22108. var scene = this.getScene();
  22109. if (!scene) {
  22110. return this._cachedTextureMatrix;
  22111. }
  22112. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22113. return mat.hasTexture(_this);
  22114. });
  22115. return this._cachedTextureMatrix;
  22116. };
  22117. Texture.prototype.getReflectionTextureMatrix = function () {
  22118. var _this = this;
  22119. var scene = this.getScene();
  22120. if (!scene) {
  22121. return this._cachedTextureMatrix;
  22122. }
  22123. if (this.uOffset === this._cachedUOffset &&
  22124. this.vOffset === this._cachedVOffset &&
  22125. this.uScale === this._cachedUScale &&
  22126. this.vScale === this._cachedVScale &&
  22127. this.coordinatesMode === this._cachedCoordinatesMode) {
  22128. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22129. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22130. return this._cachedTextureMatrix;
  22131. }
  22132. }
  22133. else {
  22134. return this._cachedTextureMatrix;
  22135. }
  22136. }
  22137. if (!this._cachedTextureMatrix) {
  22138. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22139. }
  22140. if (!this._projectionModeMatrix) {
  22141. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22142. }
  22143. this._cachedUOffset = this.uOffset;
  22144. this._cachedVOffset = this.vOffset;
  22145. this._cachedUScale = this.uScale;
  22146. this._cachedVScale = this.vScale;
  22147. this._cachedCoordinatesMode = this.coordinatesMode;
  22148. switch (this.coordinatesMode) {
  22149. case Texture.PLANAR_MODE:
  22150. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22151. this._cachedTextureMatrix[0] = this.uScale;
  22152. this._cachedTextureMatrix[5] = this.vScale;
  22153. this._cachedTextureMatrix[12] = this.uOffset;
  22154. this._cachedTextureMatrix[13] = this.vOffset;
  22155. break;
  22156. case Texture.PROJECTION_MODE:
  22157. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22158. this._projectionModeMatrix.m[0] = 0.5;
  22159. this._projectionModeMatrix.m[5] = -0.5;
  22160. this._projectionModeMatrix.m[10] = 0.0;
  22161. this._projectionModeMatrix.m[12] = 0.5;
  22162. this._projectionModeMatrix.m[13] = 0.5;
  22163. this._projectionModeMatrix.m[14] = 1.0;
  22164. this._projectionModeMatrix.m[15] = 1.0;
  22165. var projectionMatrix = scene.getProjectionMatrix();
  22166. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22167. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22168. break;
  22169. default:
  22170. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22171. break;
  22172. }
  22173. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22174. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22175. });
  22176. return this._cachedTextureMatrix;
  22177. };
  22178. Texture.prototype.clone = function () {
  22179. var _this = this;
  22180. return BABYLON.SerializationHelper.Clone(function () {
  22181. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22182. }, this);
  22183. };
  22184. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22185. get: function () {
  22186. if (!this._onLoadObservable) {
  22187. this._onLoadObservable = new BABYLON.Observable();
  22188. }
  22189. return this._onLoadObservable;
  22190. },
  22191. enumerable: true,
  22192. configurable: true
  22193. });
  22194. Texture.prototype.serialize = function () {
  22195. var serializationObject = _super.prototype.serialize.call(this);
  22196. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22197. serializationObject.base64String = this._buffer;
  22198. serializationObject.name = serializationObject.name.replace("data:", "");
  22199. }
  22200. return serializationObject;
  22201. };
  22202. Texture.prototype.getClassName = function () {
  22203. return "Texture";
  22204. };
  22205. Texture.prototype.dispose = function () {
  22206. _super.prototype.dispose.call(this);
  22207. if (this.onLoadObservable) {
  22208. this.onLoadObservable.clear();
  22209. this._onLoadObservable = null;
  22210. }
  22211. this._delayedOnLoad = null;
  22212. this._delayedOnError = null;
  22213. };
  22214. // Statics
  22215. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22216. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22217. if (onLoad === void 0) { onLoad = null; }
  22218. if (onError === void 0) { onError = null; }
  22219. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22220. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22221. };
  22222. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22223. if (parsedTexture.customType) {
  22224. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22225. // Update Sampling Mode
  22226. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22227. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22228. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22229. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22230. }
  22231. }
  22232. return parsedCustomTexture;
  22233. }
  22234. if (parsedTexture.isCube) {
  22235. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22236. }
  22237. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22238. return null;
  22239. }
  22240. var texture = BABYLON.SerializationHelper.Parse(function () {
  22241. if (parsedTexture.mirrorPlane) {
  22242. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22243. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22244. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22245. return mirrorTexture;
  22246. }
  22247. else if (parsedTexture.isRenderTarget) {
  22248. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22249. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22250. return renderTargetTexture;
  22251. }
  22252. else {
  22253. var texture;
  22254. if (parsedTexture.base64String) {
  22255. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22256. }
  22257. else {
  22258. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22259. }
  22260. return texture;
  22261. }
  22262. }, parsedTexture, scene);
  22263. // Update Sampling Mode
  22264. if (parsedTexture.samplingMode) {
  22265. var sampling = parsedTexture.samplingMode;
  22266. if (texture._samplingMode !== sampling) {
  22267. texture.updateSamplingMode(sampling);
  22268. }
  22269. }
  22270. // Animations
  22271. if (parsedTexture.animations) {
  22272. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22273. var parsedAnimation = parsedTexture.animations[animationIndex];
  22274. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22275. }
  22276. }
  22277. return texture;
  22278. };
  22279. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22280. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22281. if (noMipmap === void 0) { noMipmap = false; }
  22282. if (invertY === void 0) { invertY = true; }
  22283. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22284. if (onLoad === void 0) { onLoad = null; }
  22285. if (onError === void 0) { onError = null; }
  22286. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22287. if (name.substr(0, 5) !== "data:") {
  22288. name = "data:" + name;
  22289. }
  22290. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22291. };
  22292. // Constants
  22293. Texture.NEAREST_SAMPLINGMODE = 1;
  22294. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22295. Texture.BILINEAR_SAMPLINGMODE = 2;
  22296. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22297. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22298. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22299. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22300. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22301. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22302. Texture.NEAREST_LINEAR = 7;
  22303. Texture.NEAREST_NEAREST = 8;
  22304. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22305. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22306. Texture.LINEAR_LINEAR = 11;
  22307. Texture.LINEAR_NEAREST = 12;
  22308. Texture.EXPLICIT_MODE = 0;
  22309. Texture.SPHERICAL_MODE = 1;
  22310. Texture.PLANAR_MODE = 2;
  22311. Texture.CUBIC_MODE = 3;
  22312. Texture.PROJECTION_MODE = 4;
  22313. Texture.SKYBOX_MODE = 5;
  22314. Texture.INVCUBIC_MODE = 6;
  22315. Texture.EQUIRECTANGULAR_MODE = 7;
  22316. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22317. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22318. Texture.CLAMP_ADDRESSMODE = 0;
  22319. Texture.WRAP_ADDRESSMODE = 1;
  22320. Texture.MIRROR_ADDRESSMODE = 2;
  22321. __decorate([
  22322. BABYLON.serialize()
  22323. ], Texture.prototype, "url", void 0);
  22324. __decorate([
  22325. BABYLON.serialize()
  22326. ], Texture.prototype, "uOffset", void 0);
  22327. __decorate([
  22328. BABYLON.serialize()
  22329. ], Texture.prototype, "vOffset", void 0);
  22330. __decorate([
  22331. BABYLON.serialize()
  22332. ], Texture.prototype, "uScale", void 0);
  22333. __decorate([
  22334. BABYLON.serialize()
  22335. ], Texture.prototype, "vScale", void 0);
  22336. __decorate([
  22337. BABYLON.serialize()
  22338. ], Texture.prototype, "uAng", void 0);
  22339. __decorate([
  22340. BABYLON.serialize()
  22341. ], Texture.prototype, "vAng", void 0);
  22342. __decorate([
  22343. BABYLON.serialize()
  22344. ], Texture.prototype, "wAng", void 0);
  22345. __decorate([
  22346. BABYLON.serialize()
  22347. ], Texture.prototype, "isBlocking", null);
  22348. return Texture;
  22349. }(BABYLON.BaseTexture));
  22350. BABYLON.Texture = Texture;
  22351. })(BABYLON || (BABYLON = {}));
  22352. //# sourceMappingURL=babylon.texture.js.map
  22353. var BABYLON;
  22354. (function (BABYLON) {
  22355. var _InstancesBatch = /** @class */ (function () {
  22356. function _InstancesBatch() {
  22357. this.mustReturn = false;
  22358. this.visibleInstances = new Array();
  22359. this.renderSelf = new Array();
  22360. }
  22361. return _InstancesBatch;
  22362. }());
  22363. BABYLON._InstancesBatch = _InstancesBatch;
  22364. var Mesh = /** @class */ (function (_super) {
  22365. __extends(Mesh, _super);
  22366. /**
  22367. * @constructor
  22368. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22369. * @param {Scene} scene The scene to add this mesh to.
  22370. * @param {Node} parent The parent of this mesh, if it has one
  22371. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22372. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22373. * When false, achieved by calling a clone(), also passing False.
  22374. * This will make creation of children, recursive.
  22375. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22376. */
  22377. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22378. if (scene === void 0) { scene = null; }
  22379. if (parent === void 0) { parent = null; }
  22380. if (source === void 0) { source = null; }
  22381. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22382. var _this = _super.call(this, name, scene) || this;
  22383. // Events
  22384. /**
  22385. * An event triggered before rendering the mesh
  22386. * @type {BABYLON.Observable}
  22387. */
  22388. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22389. /**
  22390. * An event triggered after rendering the mesh
  22391. * @type {BABYLON.Observable}
  22392. */
  22393. _this.onAfterRenderObservable = new BABYLON.Observable();
  22394. /**
  22395. * An event triggered before drawing the mesh
  22396. * @type {BABYLON.Observable}
  22397. */
  22398. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22399. // Members
  22400. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22401. _this.instances = new Array();
  22402. _this._LODLevels = new Array();
  22403. _this._visibleInstances = {};
  22404. _this._renderIdForInstances = new Array();
  22405. _this._batchCache = new _InstancesBatch();
  22406. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22407. // Use by builder only to know what orientation were the mesh build in.
  22408. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22409. _this.overrideMaterialSideOrientation = null;
  22410. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22411. // Will be used to save a source mesh reference, If any
  22412. _this._source = null;
  22413. scene = _this.getScene();
  22414. if (source) {
  22415. // Source mesh
  22416. _this._source = source;
  22417. // Geometry
  22418. if (source._geometry) {
  22419. source._geometry.applyToMesh(_this);
  22420. }
  22421. // Deep copy
  22422. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22423. // Tags
  22424. if (BABYLON.Tags.HasTags(source)) {
  22425. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22426. }
  22427. _this.metadata = source.metadata;
  22428. // Parent
  22429. _this.parent = source.parent;
  22430. // Pivot
  22431. _this.setPivotMatrix(source.getPivotMatrix());
  22432. _this.id = name + "." + source.id;
  22433. // Material
  22434. _this.material = source.material;
  22435. var index;
  22436. if (!doNotCloneChildren) {
  22437. // Children
  22438. for (index = 0; index < scene.meshes.length; index++) {
  22439. var mesh = scene.meshes[index];
  22440. if (mesh.parent === source) {
  22441. // doNotCloneChildren is always going to be False
  22442. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22443. }
  22444. }
  22445. }
  22446. // Physics clone
  22447. var physicsEngine = _this.getScene().getPhysicsEngine();
  22448. if (clonePhysicsImpostor && physicsEngine) {
  22449. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22450. if (impostor) {
  22451. _this.physicsImpostor = impostor.clone(_this);
  22452. }
  22453. }
  22454. // Particles
  22455. for (index = 0; index < scene.particleSystems.length; index++) {
  22456. var system = scene.particleSystems[index];
  22457. if (system.emitter === source) {
  22458. system.clone(system.name, _this);
  22459. }
  22460. }
  22461. _this.computeWorldMatrix(true);
  22462. }
  22463. // Parent
  22464. if (parent !== null) {
  22465. _this.parent = parent;
  22466. }
  22467. return _this;
  22468. }
  22469. Object.defineProperty(Mesh, "FRONTSIDE", {
  22470. /**
  22471. * Mesh side orientation : usually the external or front surface
  22472. */
  22473. get: function () {
  22474. return Mesh._FRONTSIDE;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Object.defineProperty(Mesh, "BACKSIDE", {
  22480. /**
  22481. * Mesh side orientation : usually the internal or back surface
  22482. */
  22483. get: function () {
  22484. return Mesh._BACKSIDE;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22490. /**
  22491. * Mesh side orientation : both internal and external or front and back surfaces
  22492. */
  22493. get: function () {
  22494. return Mesh._DOUBLESIDE;
  22495. },
  22496. enumerable: true,
  22497. configurable: true
  22498. });
  22499. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22500. /**
  22501. * Mesh side orientation : by default, `FRONTSIDE`
  22502. */
  22503. get: function () {
  22504. return Mesh._DEFAULTSIDE;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Object.defineProperty(Mesh, "NO_CAP", {
  22510. /**
  22511. * Mesh cap setting : no cap
  22512. */
  22513. get: function () {
  22514. return Mesh._NO_CAP;
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. Object.defineProperty(Mesh, "CAP_START", {
  22520. /**
  22521. * Mesh cap setting : one cap at the beginning of the mesh
  22522. */
  22523. get: function () {
  22524. return Mesh._CAP_START;
  22525. },
  22526. enumerable: true,
  22527. configurable: true
  22528. });
  22529. Object.defineProperty(Mesh, "CAP_END", {
  22530. /**
  22531. * Mesh cap setting : one cap at the end of the mesh
  22532. */
  22533. get: function () {
  22534. return Mesh._CAP_END;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. Object.defineProperty(Mesh, "CAP_ALL", {
  22540. /**
  22541. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22542. */
  22543. get: function () {
  22544. return Mesh._CAP_ALL;
  22545. },
  22546. enumerable: true,
  22547. configurable: true
  22548. });
  22549. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22550. set: function (callback) {
  22551. if (this._onBeforeDrawObserver) {
  22552. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22553. }
  22554. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22555. },
  22556. enumerable: true,
  22557. configurable: true
  22558. });
  22559. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22560. get: function () {
  22561. return this._morphTargetManager;
  22562. },
  22563. set: function (value) {
  22564. if (this._morphTargetManager === value) {
  22565. return;
  22566. }
  22567. this._morphTargetManager = value;
  22568. this._syncGeometryWithMorphTargetManager();
  22569. },
  22570. enumerable: true,
  22571. configurable: true
  22572. });
  22573. Object.defineProperty(Mesh.prototype, "source", {
  22574. get: function () {
  22575. return this._source;
  22576. },
  22577. enumerable: true,
  22578. configurable: true
  22579. });
  22580. // Methods
  22581. /**
  22582. * Returns the string "Mesh".
  22583. */
  22584. Mesh.prototype.getClassName = function () {
  22585. return "Mesh";
  22586. };
  22587. /**
  22588. * Returns a string.
  22589. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22590. */
  22591. Mesh.prototype.toString = function (fullDetails) {
  22592. var ret = _super.prototype.toString.call(this, fullDetails);
  22593. ret += ", n vertices: " + this.getTotalVertices();
  22594. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22595. if (this.animations) {
  22596. for (var i = 0; i < this.animations.length; i++) {
  22597. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22598. }
  22599. }
  22600. if (fullDetails) {
  22601. if (this._geometry) {
  22602. var ib = this.getIndices();
  22603. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22604. if (vb && ib) {
  22605. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22606. }
  22607. }
  22608. else {
  22609. ret += ", flat shading: UNKNOWN";
  22610. }
  22611. }
  22612. return ret;
  22613. };
  22614. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22615. /**
  22616. * True if the mesh has some Levels Of Details (LOD).
  22617. * Returns a boolean.
  22618. */
  22619. get: function () {
  22620. return this._LODLevels.length > 0;
  22621. },
  22622. enumerable: true,
  22623. configurable: true
  22624. });
  22625. Mesh.prototype._sortLODLevels = function () {
  22626. this._LODLevels.sort(function (a, b) {
  22627. if (a.distance < b.distance) {
  22628. return 1;
  22629. }
  22630. if (a.distance > b.distance) {
  22631. return -1;
  22632. }
  22633. return 0;
  22634. });
  22635. };
  22636. /**
  22637. * Add a mesh as LOD level triggered at the given distance.
  22638. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22639. * @param {number} distance The distance from the center of the object to show this level
  22640. * @param {Mesh} mesh The mesh to be added as LOD level
  22641. * @return {Mesh} This mesh (for chaining)
  22642. */
  22643. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22644. if (mesh && mesh._masterMesh) {
  22645. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22646. return this;
  22647. }
  22648. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22649. this._LODLevels.push(level);
  22650. if (mesh) {
  22651. mesh._masterMesh = this;
  22652. }
  22653. this._sortLODLevels();
  22654. return this;
  22655. };
  22656. /**
  22657. * Returns the LOD level mesh at the passed distance or null if not found.
  22658. * It is related to the method `addLODLevel(distance, mesh)`.
  22659. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22660. * Returns an object Mesh or `null`.
  22661. */
  22662. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22663. for (var index = 0; index < this._LODLevels.length; index++) {
  22664. var level = this._LODLevels[index];
  22665. if (level.distance === distance) {
  22666. return level.mesh;
  22667. }
  22668. }
  22669. return null;
  22670. };
  22671. /**
  22672. * Remove a mesh from the LOD array
  22673. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22674. * @param {Mesh} mesh The mesh to be removed.
  22675. * @return {Mesh} This mesh (for chaining)
  22676. */
  22677. Mesh.prototype.removeLODLevel = function (mesh) {
  22678. for (var index = 0; index < this._LODLevels.length; index++) {
  22679. if (this._LODLevels[index].mesh === mesh) {
  22680. this._LODLevels.splice(index, 1);
  22681. if (mesh) {
  22682. mesh._masterMesh = null;
  22683. }
  22684. }
  22685. }
  22686. this._sortLODLevels();
  22687. return this;
  22688. };
  22689. /**
  22690. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22691. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22692. */
  22693. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22694. if (!this._LODLevels || this._LODLevels.length === 0) {
  22695. return this;
  22696. }
  22697. var bSphere;
  22698. if (boundingSphere) {
  22699. bSphere = boundingSphere;
  22700. }
  22701. else {
  22702. var boundingInfo = this.getBoundingInfo();
  22703. if (!boundingInfo) {
  22704. return this;
  22705. }
  22706. bSphere = boundingInfo.boundingSphere;
  22707. }
  22708. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22709. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22710. if (this.onLODLevelSelection) {
  22711. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22712. }
  22713. return this;
  22714. }
  22715. for (var index = 0; index < this._LODLevels.length; index++) {
  22716. var level = this._LODLevels[index];
  22717. if (level.distance < distanceToCamera) {
  22718. if (level.mesh) {
  22719. level.mesh._preActivate();
  22720. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22721. }
  22722. if (this.onLODLevelSelection) {
  22723. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22724. }
  22725. return level.mesh;
  22726. }
  22727. }
  22728. if (this.onLODLevelSelection) {
  22729. this.onLODLevelSelection(distanceToCamera, this, this);
  22730. }
  22731. return this;
  22732. };
  22733. Object.defineProperty(Mesh.prototype, "geometry", {
  22734. /**
  22735. * Returns the mesh internal Geometry object.
  22736. */
  22737. get: function () {
  22738. return this._geometry;
  22739. },
  22740. enumerable: true,
  22741. configurable: true
  22742. });
  22743. /**
  22744. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22745. */
  22746. Mesh.prototype.getTotalVertices = function () {
  22747. if (!this._geometry) {
  22748. return 0;
  22749. }
  22750. return this._geometry.getTotalVertices();
  22751. };
  22752. /**
  22753. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22754. * 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.
  22755. * You can force the copy with forceCopy === true
  22756. * Returns null if the mesh has no geometry or no vertex buffer.
  22757. * Possible `kind` values :
  22758. * - BABYLON.VertexBuffer.PositionKind
  22759. * - BABYLON.VertexBuffer.UVKind
  22760. * - BABYLON.VertexBuffer.UV2Kind
  22761. * - BABYLON.VertexBuffer.UV3Kind
  22762. * - BABYLON.VertexBuffer.UV4Kind
  22763. * - BABYLON.VertexBuffer.UV5Kind
  22764. * - BABYLON.VertexBuffer.UV6Kind
  22765. * - BABYLON.VertexBuffer.ColorKind
  22766. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22767. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22768. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22769. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22770. */
  22771. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22772. if (!this._geometry) {
  22773. return null;
  22774. }
  22775. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22776. };
  22777. /**
  22778. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22779. * Returns `null` if the mesh has no geometry.
  22780. * Possible `kind` values :
  22781. * - BABYLON.VertexBuffer.PositionKind
  22782. * - BABYLON.VertexBuffer.UVKind
  22783. * - BABYLON.VertexBuffer.UV2Kind
  22784. * - BABYLON.VertexBuffer.UV3Kind
  22785. * - BABYLON.VertexBuffer.UV4Kind
  22786. * - BABYLON.VertexBuffer.UV5Kind
  22787. * - BABYLON.VertexBuffer.UV6Kind
  22788. * - BABYLON.VertexBuffer.ColorKind
  22789. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22790. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22791. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22792. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22793. */
  22794. Mesh.prototype.getVertexBuffer = function (kind) {
  22795. if (!this._geometry) {
  22796. return null;
  22797. }
  22798. return this._geometry.getVertexBuffer(kind);
  22799. };
  22800. /**
  22801. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22802. * Possible `kind` values :
  22803. * - BABYLON.VertexBuffer.PositionKind
  22804. * - BABYLON.VertexBuffer.UVKind
  22805. * - BABYLON.VertexBuffer.UV2Kind
  22806. * - BABYLON.VertexBuffer.UV3Kind
  22807. * - BABYLON.VertexBuffer.UV4Kind
  22808. * - BABYLON.VertexBuffer.UV5Kind
  22809. * - BABYLON.VertexBuffer.UV6Kind
  22810. * - BABYLON.VertexBuffer.ColorKind
  22811. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22812. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22813. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22814. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22815. */
  22816. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22817. if (!this._geometry) {
  22818. if (this._delayInfo) {
  22819. return this._delayInfo.indexOf(kind) !== -1;
  22820. }
  22821. return false;
  22822. }
  22823. return this._geometry.isVerticesDataPresent(kind);
  22824. };
  22825. /**
  22826. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22827. * Possible `kind` values :
  22828. * - BABYLON.VertexBuffer.PositionKind
  22829. * - BABYLON.VertexBuffer.UVKind
  22830. * - BABYLON.VertexBuffer.UV2Kind
  22831. * - BABYLON.VertexBuffer.UV3Kind
  22832. * - BABYLON.VertexBuffer.UV4Kind
  22833. * - BABYLON.VertexBuffer.UV5Kind
  22834. * - BABYLON.VertexBuffer.UV6Kind
  22835. * - BABYLON.VertexBuffer.ColorKind
  22836. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22837. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22838. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22839. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22840. */
  22841. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22842. if (!this._geometry) {
  22843. if (this._delayInfo) {
  22844. return this._delayInfo.indexOf(kind) !== -1;
  22845. }
  22846. return false;
  22847. }
  22848. return this._geometry.isVertexBufferUpdatable(kind);
  22849. };
  22850. /**
  22851. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22852. * Possible `kind` values :
  22853. * - BABYLON.VertexBuffer.PositionKind
  22854. * - BABYLON.VertexBuffer.UVKind
  22855. * - BABYLON.VertexBuffer.UV2Kind
  22856. * - BABYLON.VertexBuffer.UV3Kind
  22857. * - BABYLON.VertexBuffer.UV4Kind
  22858. * - BABYLON.VertexBuffer.UV5Kind
  22859. * - BABYLON.VertexBuffer.UV6Kind
  22860. * - BABYLON.VertexBuffer.ColorKind
  22861. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22862. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22863. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22864. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22865. */
  22866. Mesh.prototype.getVerticesDataKinds = function () {
  22867. if (!this._geometry) {
  22868. var result = new Array();
  22869. if (this._delayInfo) {
  22870. this._delayInfo.forEach(function (kind, index, array) {
  22871. result.push(kind);
  22872. });
  22873. }
  22874. return result;
  22875. }
  22876. return this._geometry.getVerticesDataKinds();
  22877. };
  22878. /**
  22879. * Returns a positive integer : the total number of indices in this mesh geometry.
  22880. * Returns zero if the mesh has no geometry.
  22881. */
  22882. Mesh.prototype.getTotalIndices = function () {
  22883. if (!this._geometry) {
  22884. return 0;
  22885. }
  22886. return this._geometry.getTotalIndices();
  22887. };
  22888. /**
  22889. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22890. * 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.
  22891. * Returns an empty array if the mesh has no geometry.
  22892. */
  22893. Mesh.prototype.getIndices = function (copyWhenShared) {
  22894. if (!this._geometry) {
  22895. return [];
  22896. }
  22897. return this._geometry.getIndices(copyWhenShared);
  22898. };
  22899. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22900. get: function () {
  22901. return this._masterMesh !== null && this._masterMesh !== undefined;
  22902. },
  22903. enumerable: true,
  22904. configurable: true
  22905. });
  22906. /**
  22907. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22908. */
  22909. Mesh.prototype.isReady = function () {
  22910. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22911. return false;
  22912. }
  22913. return _super.prototype.isReady.call(this);
  22914. };
  22915. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22916. /**
  22917. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22918. * This property is pertinent only for updatable parametric shapes.
  22919. */
  22920. get: function () {
  22921. return this._areNormalsFrozen;
  22922. },
  22923. enumerable: true,
  22924. configurable: true
  22925. });
  22926. /**
  22927. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22928. * It has no effect at all on other shapes.
  22929. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22930. * Returns the Mesh.
  22931. */
  22932. Mesh.prototype.freezeNormals = function () {
  22933. this._areNormalsFrozen = true;
  22934. return this;
  22935. };
  22936. /**
  22937. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22938. * It has no effect at all on other shapes.
  22939. * It reactivates the mesh normals computation if it was previously frozen.
  22940. * Returns the Mesh.
  22941. */
  22942. Mesh.prototype.unfreezeNormals = function () {
  22943. this._areNormalsFrozen = false;
  22944. return this;
  22945. };
  22946. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22947. /**
  22948. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22949. */
  22950. set: function (count) {
  22951. this._overridenInstanceCount = count;
  22952. },
  22953. enumerable: true,
  22954. configurable: true
  22955. });
  22956. // Methods
  22957. Mesh.prototype._preActivate = function () {
  22958. var sceneRenderId = this.getScene().getRenderId();
  22959. if (this._preActivateId === sceneRenderId) {
  22960. return this;
  22961. }
  22962. this._preActivateId = sceneRenderId;
  22963. this._visibleInstances = null;
  22964. return this;
  22965. };
  22966. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22967. if (this._visibleInstances) {
  22968. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22969. }
  22970. return this;
  22971. };
  22972. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22973. if (!this._visibleInstances) {
  22974. this._visibleInstances = {};
  22975. this._visibleInstances.defaultRenderId = renderId;
  22976. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22977. }
  22978. if (!this._visibleInstances[renderId]) {
  22979. this._visibleInstances[renderId] = new Array();
  22980. }
  22981. this._visibleInstances[renderId].push(instance);
  22982. return this;
  22983. };
  22984. /**
  22985. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22986. * This means the mesh underlying bounding box and sphere are recomputed.
  22987. * Returns the Mesh.
  22988. */
  22989. Mesh.prototype.refreshBoundingInfo = function () {
  22990. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22991. return this;
  22992. }
  22993. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22994. if (data) {
  22995. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22996. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22997. }
  22998. if (this.subMeshes) {
  22999. for (var index = 0; index < this.subMeshes.length; index++) {
  23000. this.subMeshes[index].refreshBoundingInfo();
  23001. }
  23002. }
  23003. this._updateBoundingInfo();
  23004. return this;
  23005. };
  23006. Mesh.prototype._createGlobalSubMesh = function (force) {
  23007. var totalVertices = this.getTotalVertices();
  23008. if (!totalVertices || !this.getIndices()) {
  23009. return null;
  23010. }
  23011. // Check if we need to recreate the submeshes
  23012. if (this.subMeshes && this.subMeshes.length > 0) {
  23013. var ib = this.getIndices();
  23014. if (!ib) {
  23015. return null;
  23016. }
  23017. var totalIndices = ib.length;
  23018. var needToRecreate = false;
  23019. if (force) {
  23020. needToRecreate = true;
  23021. }
  23022. else {
  23023. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23024. var submesh = _a[_i];
  23025. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23026. needToRecreate = true;
  23027. break;
  23028. }
  23029. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23030. needToRecreate = true;
  23031. break;
  23032. }
  23033. }
  23034. }
  23035. if (!needToRecreate) {
  23036. return this.subMeshes[0];
  23037. }
  23038. }
  23039. this.releaseSubMeshes();
  23040. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23041. };
  23042. Mesh.prototype.subdivide = function (count) {
  23043. if (count < 1) {
  23044. return;
  23045. }
  23046. var totalIndices = this.getTotalIndices();
  23047. var subdivisionSize = (totalIndices / count) | 0;
  23048. var offset = 0;
  23049. // Ensure that subdivisionSize is a multiple of 3
  23050. while (subdivisionSize % 3 !== 0) {
  23051. subdivisionSize++;
  23052. }
  23053. this.releaseSubMeshes();
  23054. for (var index = 0; index < count; index++) {
  23055. if (offset >= totalIndices) {
  23056. break;
  23057. }
  23058. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23059. offset += subdivisionSize;
  23060. }
  23061. this.synchronizeInstances();
  23062. };
  23063. /**
  23064. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23065. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23066. * The `data` are either a numeric array either a Float32Array.
  23067. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23068. * 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).
  23069. * Note that a new underlying VertexBuffer object is created each call.
  23070. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23071. *
  23072. * Possible `kind` values :
  23073. * - BABYLON.VertexBuffer.PositionKind
  23074. * - BABYLON.VertexBuffer.UVKind
  23075. * - BABYLON.VertexBuffer.UV2Kind
  23076. * - BABYLON.VertexBuffer.UV3Kind
  23077. * - BABYLON.VertexBuffer.UV4Kind
  23078. * - BABYLON.VertexBuffer.UV5Kind
  23079. * - BABYLON.VertexBuffer.UV6Kind
  23080. * - BABYLON.VertexBuffer.ColorKind
  23081. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23082. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23083. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23084. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23085. *
  23086. * Returns the Mesh.
  23087. */
  23088. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23089. if (updatable === void 0) { updatable = false; }
  23090. if (!this._geometry) {
  23091. var vertexData = new BABYLON.VertexData();
  23092. vertexData.set(data, kind);
  23093. var scene = this.getScene();
  23094. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23095. }
  23096. else {
  23097. this._geometry.setVerticesData(kind, data, updatable, stride);
  23098. }
  23099. return this;
  23100. };
  23101. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23102. if (updatable === void 0) { updatable = true; }
  23103. var vb = this.getVertexBuffer(kind);
  23104. if (!vb || vb.isUpdatable() === updatable) {
  23105. return;
  23106. }
  23107. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23108. };
  23109. /**
  23110. * Sets the mesh VertexBuffer.
  23111. * Returns the Mesh.
  23112. */
  23113. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23114. if (!this._geometry) {
  23115. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23116. }
  23117. this._geometry.setVerticesBuffer(buffer);
  23118. return this;
  23119. };
  23120. /**
  23121. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23122. * If the mesh has no geometry, it is simply returned as it is.
  23123. * The `data` are either a numeric array either a Float32Array.
  23124. * No new underlying VertexBuffer object is created.
  23125. * 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.
  23126. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23127. *
  23128. * Possible `kind` values :
  23129. * - BABYLON.VertexBuffer.PositionKind
  23130. * - BABYLON.VertexBuffer.UVKind
  23131. * - BABYLON.VertexBuffer.UV2Kind
  23132. * - BABYLON.VertexBuffer.UV3Kind
  23133. * - BABYLON.VertexBuffer.UV4Kind
  23134. * - BABYLON.VertexBuffer.UV5Kind
  23135. * - BABYLON.VertexBuffer.UV6Kind
  23136. * - BABYLON.VertexBuffer.ColorKind
  23137. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23138. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23139. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23140. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23141. *
  23142. * Returns the Mesh.
  23143. */
  23144. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23145. if (!this._geometry) {
  23146. return this;
  23147. }
  23148. if (!makeItUnique) {
  23149. this._geometry.updateVerticesData(kind, data, updateExtends);
  23150. }
  23151. else {
  23152. this.makeGeometryUnique();
  23153. this.updateVerticesData(kind, data, updateExtends, false);
  23154. }
  23155. return this;
  23156. };
  23157. /**
  23158. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23159. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23160. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23161. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23162. * Returns the Mesh.
  23163. */
  23164. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23165. if (computeNormals === void 0) { computeNormals = true; }
  23166. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23167. if (!positions) {
  23168. return this;
  23169. }
  23170. positionFunction(positions);
  23171. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23172. if (computeNormals) {
  23173. var indices = this.getIndices();
  23174. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23175. if (!normals) {
  23176. return this;
  23177. }
  23178. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23179. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23180. }
  23181. return this;
  23182. };
  23183. /**
  23184. * Creates a un-shared specific occurence of the geometry for the mesh.
  23185. * Returns the Mesh.
  23186. */
  23187. Mesh.prototype.makeGeometryUnique = function () {
  23188. if (!this._geometry) {
  23189. return this;
  23190. }
  23191. var oldGeometry = this._geometry;
  23192. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23193. oldGeometry.releaseForMesh(this, true);
  23194. geometry.applyToMesh(this);
  23195. return this;
  23196. };
  23197. /**
  23198. * Sets the mesh indices.
  23199. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23200. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23201. * This method creates a new index buffer each call.
  23202. * Returns the Mesh.
  23203. */
  23204. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23205. if (totalVertices === void 0) { totalVertices = null; }
  23206. if (updatable === void 0) { updatable = false; }
  23207. if (!this._geometry) {
  23208. var vertexData = new BABYLON.VertexData();
  23209. vertexData.indices = indices;
  23210. var scene = this.getScene();
  23211. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23212. }
  23213. else {
  23214. this._geometry.setIndices(indices, totalVertices, updatable);
  23215. }
  23216. return this;
  23217. };
  23218. /**
  23219. * Update the current index buffer
  23220. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23221. * Returns the Mesh.
  23222. */
  23223. Mesh.prototype.updateIndices = function (indices, offset) {
  23224. if (!this._geometry) {
  23225. return this;
  23226. }
  23227. this._geometry.updateIndices(indices, offset);
  23228. return this;
  23229. };
  23230. /**
  23231. * Invert the geometry to move from a right handed system to a left handed one.
  23232. * Returns the Mesh.
  23233. */
  23234. Mesh.prototype.toLeftHanded = function () {
  23235. if (!this._geometry) {
  23236. return this;
  23237. }
  23238. this._geometry.toLeftHanded();
  23239. return this;
  23240. };
  23241. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23242. if (!this._geometry) {
  23243. return this;
  23244. }
  23245. var engine = this.getScene().getEngine();
  23246. // Wireframe
  23247. var indexToBind;
  23248. if (this._unIndexed) {
  23249. indexToBind = null;
  23250. }
  23251. else {
  23252. switch (fillMode) {
  23253. case BABYLON.Material.PointFillMode:
  23254. indexToBind = null;
  23255. break;
  23256. case BABYLON.Material.WireFrameFillMode:
  23257. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23258. break;
  23259. default:
  23260. case BABYLON.Material.TriangleFillMode:
  23261. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23262. break;
  23263. }
  23264. }
  23265. // VBOs
  23266. this._geometry._bind(effect, indexToBind);
  23267. return this;
  23268. };
  23269. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23270. if (alternate === void 0) { alternate = false; }
  23271. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23272. return this;
  23273. }
  23274. this.onBeforeDrawObservable.notifyObservers(this);
  23275. var scene = this.getScene();
  23276. var engine = scene.getEngine();
  23277. // Draw order
  23278. switch (fillMode) {
  23279. case BABYLON.Material.PointFillMode:
  23280. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23281. break;
  23282. case BABYLON.Material.WireFrameFillMode:
  23283. if (this._unIndexed) {
  23284. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23285. }
  23286. else {
  23287. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23288. }
  23289. break;
  23290. default:
  23291. if (this._unIndexed) {
  23292. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23293. }
  23294. else {
  23295. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23296. }
  23297. }
  23298. if (scene._isAlternateRenderingEnabled && !alternate) {
  23299. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23300. if (!effect || !scene.activeCamera) {
  23301. return this;
  23302. }
  23303. scene._switchToAlternateCameraConfiguration(true);
  23304. this._effectiveMaterial.bindView(effect);
  23305. this._effectiveMaterial.bindViewProjection(effect);
  23306. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23307. this._draw(subMesh, fillMode, instancesCount, true);
  23308. engine.setViewport(scene.activeCamera.viewport);
  23309. scene._switchToAlternateCameraConfiguration(false);
  23310. this._effectiveMaterial.bindView(effect);
  23311. this._effectiveMaterial.bindViewProjection(effect);
  23312. }
  23313. return this;
  23314. };
  23315. /**
  23316. * Registers for this mesh a javascript function called just before the rendering process.
  23317. * This function is passed the current mesh.
  23318. * Return the Mesh.
  23319. */
  23320. Mesh.prototype.registerBeforeRender = function (func) {
  23321. this.onBeforeRenderObservable.add(func);
  23322. return this;
  23323. };
  23324. /**
  23325. * Disposes a previously registered javascript function called before the rendering.
  23326. * This function is passed the current mesh.
  23327. * Returns the Mesh.
  23328. */
  23329. Mesh.prototype.unregisterBeforeRender = function (func) {
  23330. this.onBeforeRenderObservable.removeCallback(func);
  23331. return this;
  23332. };
  23333. /**
  23334. * Registers for this mesh a javascript function called just after the rendering is complete.
  23335. * This function is passed the current mesh.
  23336. * Returns the Mesh.
  23337. */
  23338. Mesh.prototype.registerAfterRender = function (func) {
  23339. this.onAfterRenderObservable.add(func);
  23340. return this;
  23341. };
  23342. /**
  23343. * Disposes a previously registered javascript function called after the rendering.
  23344. * This function is passed the current mesh.
  23345. * Return the Mesh.
  23346. */
  23347. Mesh.prototype.unregisterAfterRender = function (func) {
  23348. this.onAfterRenderObservable.removeCallback(func);
  23349. return this;
  23350. };
  23351. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23352. var scene = this.getScene();
  23353. this._batchCache.mustReturn = false;
  23354. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23355. this._batchCache.visibleInstances[subMeshId] = null;
  23356. if (this._visibleInstances) {
  23357. var currentRenderId = scene.getRenderId();
  23358. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23359. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23360. var selfRenderId = this._renderId;
  23361. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23362. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23363. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23364. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23365. }
  23366. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23367. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23368. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23369. this._batchCache.mustReturn = true;
  23370. return this._batchCache;
  23371. }
  23372. if (currentRenderId !== selfRenderId) {
  23373. this._batchCache.renderSelf[subMeshId] = false;
  23374. }
  23375. }
  23376. this._renderIdForInstances[subMeshId] = currentRenderId;
  23377. }
  23378. return this._batchCache;
  23379. };
  23380. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23381. var visibleInstances = batch.visibleInstances[subMesh._id];
  23382. if (!visibleInstances) {
  23383. return this;
  23384. }
  23385. var matricesCount = visibleInstances.length + 1;
  23386. var bufferSize = matricesCount * 16 * 4;
  23387. var currentInstancesBufferSize = this._instancesBufferSize;
  23388. var instancesBuffer = this._instancesBuffer;
  23389. while (this._instancesBufferSize < bufferSize) {
  23390. this._instancesBufferSize *= 2;
  23391. }
  23392. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23393. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23394. }
  23395. var offset = 0;
  23396. var instancesCount = 0;
  23397. var world = this.getWorldMatrix();
  23398. if (batch.renderSelf[subMesh._id]) {
  23399. world.copyToArray(this._instancesData, offset);
  23400. offset += 16;
  23401. instancesCount++;
  23402. }
  23403. if (visibleInstances) {
  23404. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23405. var instance = visibleInstances[instanceIndex];
  23406. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23407. offset += 16;
  23408. instancesCount++;
  23409. }
  23410. }
  23411. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23412. if (instancesBuffer) {
  23413. instancesBuffer.dispose();
  23414. }
  23415. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23416. this._instancesBuffer = instancesBuffer;
  23417. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23418. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23419. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23420. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23421. }
  23422. else {
  23423. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23424. }
  23425. this._bind(subMesh, effect, fillMode);
  23426. this._draw(subMesh, fillMode, instancesCount);
  23427. engine.unbindInstanceAttributes();
  23428. return this;
  23429. };
  23430. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23431. var scene = this.getScene();
  23432. var engine = scene.getEngine();
  23433. if (hardwareInstancedRendering) {
  23434. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23435. }
  23436. else {
  23437. if (batch.renderSelf[subMesh._id]) {
  23438. // Draw
  23439. if (onBeforeDraw) {
  23440. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23441. }
  23442. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23443. }
  23444. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23445. if (visibleInstancesForSubMesh) {
  23446. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23447. var instance = visibleInstancesForSubMesh[instanceIndex];
  23448. // World
  23449. var world = instance.getWorldMatrix();
  23450. if (onBeforeDraw) {
  23451. onBeforeDraw(true, world, effectiveMaterial);
  23452. }
  23453. // Draw
  23454. this._draw(subMesh, fillMode);
  23455. }
  23456. }
  23457. }
  23458. return this;
  23459. };
  23460. /**
  23461. * Triggers the draw call for the mesh.
  23462. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23463. * Returns the Mesh.
  23464. */
  23465. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23466. this.checkOcclusionQuery();
  23467. if (this._isOccluded) {
  23468. return this;
  23469. }
  23470. var scene = this.getScene();
  23471. // Managing instances
  23472. var batch = this._getInstancesRenderList(subMesh._id);
  23473. if (batch.mustReturn) {
  23474. return this;
  23475. }
  23476. // Checking geometry state
  23477. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23478. return this;
  23479. }
  23480. this.onBeforeRenderObservable.notifyObservers(this);
  23481. var engine = scene.getEngine();
  23482. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23483. // Material
  23484. var material = subMesh.getMaterial();
  23485. if (!material) {
  23486. return this;
  23487. }
  23488. this._effectiveMaterial = material;
  23489. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23490. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23491. return this;
  23492. }
  23493. }
  23494. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23495. return this;
  23496. }
  23497. // Alpha mode
  23498. if (enableAlphaMode) {
  23499. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23500. }
  23501. // Outline - step 1
  23502. var savedDepthWrite = engine.getDepthWrite();
  23503. if (this.renderOutline) {
  23504. engine.setDepthWrite(false);
  23505. scene.getOutlineRenderer().render(subMesh, batch);
  23506. engine.setDepthWrite(savedDepthWrite);
  23507. }
  23508. var effect;
  23509. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23510. effect = subMesh.effect;
  23511. }
  23512. else {
  23513. effect = this._effectiveMaterial.getEffect();
  23514. }
  23515. if (!effect) {
  23516. return this;
  23517. }
  23518. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23519. if (this._effectiveMaterial.forceDepthWrite) {
  23520. engine.setDepthWrite(true);
  23521. }
  23522. // Bind
  23523. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23524. if (!hardwareInstancedRendering) {
  23525. this._bind(subMesh, effect, fillMode);
  23526. }
  23527. var world = this.getWorldMatrix();
  23528. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23529. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23530. }
  23531. else {
  23532. this._effectiveMaterial.bind(world, this);
  23533. }
  23534. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23535. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23536. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23537. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23538. }
  23539. // Draw
  23540. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23541. // Unbind
  23542. this._effectiveMaterial.unbind();
  23543. // Outline - step 2
  23544. if (this.renderOutline && savedDepthWrite) {
  23545. engine.setDepthWrite(true);
  23546. engine.setColorWrite(false);
  23547. scene.getOutlineRenderer().render(subMesh, batch);
  23548. engine.setColorWrite(true);
  23549. }
  23550. // Overlay
  23551. if (this.renderOverlay) {
  23552. var currentMode = engine.getAlphaMode();
  23553. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23554. scene.getOutlineRenderer().render(subMesh, batch, true);
  23555. engine.setAlphaMode(currentMode);
  23556. }
  23557. this.onAfterRenderObservable.notifyObservers(this);
  23558. return this;
  23559. };
  23560. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23561. if (isInstance) {
  23562. effectiveMaterial.bindOnlyWorldMatrix(world);
  23563. }
  23564. return this;
  23565. };
  23566. /**
  23567. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23568. */
  23569. Mesh.prototype.getEmittedParticleSystems = function () {
  23570. var results = new Array();
  23571. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23572. var particleSystem = this.getScene().particleSystems[index];
  23573. if (particleSystem.emitter === this) {
  23574. results.push(particleSystem);
  23575. }
  23576. }
  23577. return results;
  23578. };
  23579. /**
  23580. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23581. */
  23582. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23583. var results = new Array();
  23584. var descendants = this.getDescendants();
  23585. descendants.push(this);
  23586. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23587. var particleSystem = this.getScene().particleSystems[index];
  23588. var emitter = particleSystem.emitter;
  23589. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23590. results.push(particleSystem);
  23591. }
  23592. }
  23593. return results;
  23594. };
  23595. Mesh.prototype._checkDelayState = function () {
  23596. var scene = this.getScene();
  23597. if (this._geometry) {
  23598. this._geometry.load(scene);
  23599. }
  23600. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23601. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23602. this._queueLoad(this, scene);
  23603. }
  23604. return this;
  23605. };
  23606. Mesh.prototype._queueLoad = function (mesh, scene) {
  23607. var _this = this;
  23608. scene._addPendingData(mesh);
  23609. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23610. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23611. if (data instanceof ArrayBuffer) {
  23612. _this._delayLoadingFunction(data, _this);
  23613. }
  23614. else {
  23615. _this._delayLoadingFunction(JSON.parse(data), _this);
  23616. }
  23617. _this.instances.forEach(function (instance) {
  23618. instance._syncSubMeshes();
  23619. });
  23620. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23621. scene._removePendingData(_this);
  23622. }, function () { }, scene.database, getBinaryData);
  23623. return this;
  23624. };
  23625. /**
  23626. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23627. */
  23628. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23629. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23630. return false;
  23631. }
  23632. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23633. return false;
  23634. }
  23635. this._checkDelayState();
  23636. return true;
  23637. };
  23638. /**
  23639. * Sets the mesh material by the material or multiMaterial `id` property.
  23640. * The material `id` is a string identifying the material or the multiMaterial.
  23641. * This method returns the Mesh.
  23642. */
  23643. Mesh.prototype.setMaterialByID = function (id) {
  23644. var materials = this.getScene().materials;
  23645. var index;
  23646. for (index = materials.length - 1; index > -1; index--) {
  23647. if (materials[index].id === id) {
  23648. this.material = materials[index];
  23649. return this;
  23650. }
  23651. }
  23652. // Multi
  23653. var multiMaterials = this.getScene().multiMaterials;
  23654. for (index = multiMaterials.length - 1; index > -1; index--) {
  23655. if (multiMaterials[index].id === id) {
  23656. this.material = multiMaterials[index];
  23657. return this;
  23658. }
  23659. }
  23660. return this;
  23661. };
  23662. /**
  23663. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23664. */
  23665. Mesh.prototype.getAnimatables = function () {
  23666. var results = new Array();
  23667. if (this.material) {
  23668. results.push(this.material);
  23669. }
  23670. if (this.skeleton) {
  23671. results.push(this.skeleton);
  23672. }
  23673. return results;
  23674. };
  23675. /**
  23676. * Modifies the mesh geometry according to the passed transformation matrix.
  23677. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23678. * The mesh normals are modified accordingly the same transformation.
  23679. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23680. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23681. * Returns the Mesh.
  23682. */
  23683. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23684. // Position
  23685. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23686. return this;
  23687. }
  23688. var submeshes = this.subMeshes.splice(0);
  23689. this._resetPointsArrayCache();
  23690. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23691. var temp = new Array();
  23692. var index;
  23693. for (index = 0; index < data.length; index += 3) {
  23694. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23695. }
  23696. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23697. // Normals
  23698. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23699. return this;
  23700. }
  23701. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23702. temp = [];
  23703. for (index = 0; index < data.length; index += 3) {
  23704. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23705. }
  23706. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23707. // flip faces?
  23708. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23709. this.flipFaces();
  23710. }
  23711. // Restore submeshes
  23712. this.releaseSubMeshes();
  23713. this.subMeshes = submeshes;
  23714. return this;
  23715. };
  23716. /**
  23717. * Modifies the mesh geometry according to its own current World Matrix.
  23718. * The mesh World Matrix is then reset.
  23719. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23720. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23721. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23722. * Returns the Mesh.
  23723. */
  23724. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23725. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23726. this.scaling.copyFromFloats(1, 1, 1);
  23727. this.position.copyFromFloats(0, 0, 0);
  23728. this.rotation.copyFromFloats(0, 0, 0);
  23729. //only if quaternion is already set
  23730. if (this.rotationQuaternion) {
  23731. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23732. }
  23733. this._worldMatrix = BABYLON.Matrix.Identity();
  23734. return this;
  23735. };
  23736. Object.defineProperty(Mesh.prototype, "_positions", {
  23737. // Cache
  23738. get: function () {
  23739. if (this._geometry) {
  23740. return this._geometry._positions;
  23741. }
  23742. return null;
  23743. },
  23744. enumerable: true,
  23745. configurable: true
  23746. });
  23747. Mesh.prototype._resetPointsArrayCache = function () {
  23748. if (this._geometry) {
  23749. this._geometry._resetPointsArrayCache();
  23750. }
  23751. return this;
  23752. };
  23753. Mesh.prototype._generatePointsArray = function () {
  23754. if (this._geometry) {
  23755. return this._geometry._generatePointsArray();
  23756. }
  23757. return false;
  23758. };
  23759. /**
  23760. * Returns a new Mesh object generated from the current mesh properties.
  23761. * This method must not get confused with createInstance().
  23762. * The parameter `name` is a string, the name given to the new mesh.
  23763. * The optional parameter `newParent` can be any Node object (default `null`).
  23764. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23765. * 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.
  23766. */
  23767. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23768. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23769. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23770. };
  23771. /**
  23772. * Disposes the mesh.
  23773. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23774. */
  23775. Mesh.prototype.dispose = function (doNotRecurse) {
  23776. var _this = this;
  23777. this.morphTargetManager = null;
  23778. if (this._geometry) {
  23779. this._geometry.releaseForMesh(this, true);
  23780. }
  23781. // Sources
  23782. var meshes = this.getScene().meshes;
  23783. meshes.forEach(function (mesh) {
  23784. if (mesh._source && mesh._source === _this) {
  23785. mesh._source = null;
  23786. }
  23787. });
  23788. this._source = null;
  23789. // Instances
  23790. if (this._instancesBuffer) {
  23791. this._instancesBuffer.dispose();
  23792. this._instancesBuffer = null;
  23793. }
  23794. while (this.instances.length) {
  23795. this.instances[0].dispose();
  23796. }
  23797. // Highlight layers.
  23798. var highlightLayers = this.getScene().highlightLayers;
  23799. for (var i = 0; i < highlightLayers.length; i++) {
  23800. var highlightLayer = highlightLayers[i];
  23801. if (highlightLayer) {
  23802. highlightLayer.removeMesh(this);
  23803. highlightLayer.removeExcludedMesh(this);
  23804. }
  23805. }
  23806. _super.prototype.dispose.call(this, doNotRecurse);
  23807. };
  23808. /**
  23809. * Modifies the mesh geometry according to a displacement map.
  23810. * 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.
  23811. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23812. * This method returns nothing.
  23813. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23814. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23815. * 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.
  23816. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23817. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23818. *
  23819. * Returns the Mesh.
  23820. */
  23821. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23822. var _this = this;
  23823. var scene = this.getScene();
  23824. var onload = function (img) {
  23825. // Getting height map data
  23826. var canvas = document.createElement("canvas");
  23827. var context = canvas.getContext("2d");
  23828. var heightMapWidth = img.width;
  23829. var heightMapHeight = img.height;
  23830. canvas.width = heightMapWidth;
  23831. canvas.height = heightMapHeight;
  23832. context.drawImage(img, 0, 0);
  23833. // Create VertexData from map data
  23834. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23835. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23836. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23837. //execute success callback, if set
  23838. if (onSuccess) {
  23839. onSuccess(_this);
  23840. }
  23841. };
  23842. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23843. return this;
  23844. };
  23845. /**
  23846. * Modifies the mesh geometry according to a displacementMap buffer.
  23847. * 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.
  23848. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23849. * This method returns nothing.
  23850. * 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.
  23851. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23852. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23853. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23854. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23855. *
  23856. * Returns the Mesh.
  23857. */
  23858. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23859. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23860. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23861. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23862. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23863. return this;
  23864. }
  23865. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23866. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23867. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23868. var position = BABYLON.Vector3.Zero();
  23869. var normal = BABYLON.Vector3.Zero();
  23870. var uv = BABYLON.Vector2.Zero();
  23871. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23872. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23873. for (var index = 0; index < positions.length; index += 3) {
  23874. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23875. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23876. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23877. // Compute height
  23878. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23879. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23880. var pos = (u + v * heightMapWidth) * 4;
  23881. var r = buffer[pos] / 255.0;
  23882. var g = buffer[pos + 1] / 255.0;
  23883. var b = buffer[pos + 2] / 255.0;
  23884. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23885. normal.normalize();
  23886. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23887. position = position.add(normal);
  23888. position.toArray(positions, index);
  23889. }
  23890. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23891. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23892. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23893. return this;
  23894. };
  23895. /**
  23896. * Modify the mesh to get a flat shading rendering.
  23897. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23898. * This method returns the Mesh.
  23899. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23900. */
  23901. Mesh.prototype.convertToFlatShadedMesh = function () {
  23902. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23903. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23904. var kinds = this.getVerticesDataKinds();
  23905. var vbs = {};
  23906. var data = {};
  23907. var newdata = {};
  23908. var updatableNormals = false;
  23909. var kindIndex;
  23910. var kind;
  23911. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23912. kind = kinds[kindIndex];
  23913. var vertexBuffer = this.getVertexBuffer(kind);
  23914. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23915. updatableNormals = vertexBuffer.isUpdatable();
  23916. kinds.splice(kindIndex, 1);
  23917. kindIndex--;
  23918. continue;
  23919. }
  23920. vbs[kind] = vertexBuffer;
  23921. data[kind] = vbs[kind].getData();
  23922. newdata[kind] = [];
  23923. }
  23924. // Save previous submeshes
  23925. var previousSubmeshes = this.subMeshes.slice(0);
  23926. var indices = this.getIndices();
  23927. var totalIndices = this.getTotalIndices();
  23928. // Generating unique vertices per face
  23929. var index;
  23930. for (index = 0; index < totalIndices; index++) {
  23931. var vertexIndex = indices[index];
  23932. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23933. kind = kinds[kindIndex];
  23934. var stride = vbs[kind].getStrideSize();
  23935. for (var offset = 0; offset < stride; offset++) {
  23936. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23937. }
  23938. }
  23939. }
  23940. // Updating faces & normal
  23941. var normals = [];
  23942. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23943. for (index = 0; index < totalIndices; index += 3) {
  23944. indices[index] = index;
  23945. indices[index + 1] = index + 1;
  23946. indices[index + 2] = index + 2;
  23947. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23948. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23949. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23950. var p1p2 = p1.subtract(p2);
  23951. var p3p2 = p3.subtract(p2);
  23952. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23953. // Store same normals for every vertex
  23954. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23955. normals.push(normal.x);
  23956. normals.push(normal.y);
  23957. normals.push(normal.z);
  23958. }
  23959. }
  23960. this.setIndices(indices);
  23961. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23962. // Updating vertex buffers
  23963. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23964. kind = kinds[kindIndex];
  23965. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23966. }
  23967. // Updating submeshes
  23968. this.releaseSubMeshes();
  23969. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23970. var previousOne = previousSubmeshes[submeshIndex];
  23971. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23972. }
  23973. this.synchronizeInstances();
  23974. return this;
  23975. };
  23976. /**
  23977. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23978. * In other words, more vertices, no more indices and a single bigger VBO.
  23979. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23980. * Returns the Mesh.
  23981. */
  23982. Mesh.prototype.convertToUnIndexedMesh = function () {
  23983. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23984. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23985. var kinds = this.getVerticesDataKinds();
  23986. var vbs = {};
  23987. var data = {};
  23988. var newdata = {};
  23989. var kindIndex;
  23990. var kind;
  23991. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23992. kind = kinds[kindIndex];
  23993. var vertexBuffer = this.getVertexBuffer(kind);
  23994. vbs[kind] = vertexBuffer;
  23995. data[kind] = vbs[kind].getData();
  23996. newdata[kind] = [];
  23997. }
  23998. // Save previous submeshes
  23999. var previousSubmeshes = this.subMeshes.slice(0);
  24000. var indices = this.getIndices();
  24001. var totalIndices = this.getTotalIndices();
  24002. // Generating unique vertices per face
  24003. var index;
  24004. for (index = 0; index < totalIndices; index++) {
  24005. var vertexIndex = indices[index];
  24006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24007. kind = kinds[kindIndex];
  24008. var stride = vbs[kind].getStrideSize();
  24009. for (var offset = 0; offset < stride; offset++) {
  24010. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24011. }
  24012. }
  24013. }
  24014. // Updating indices
  24015. for (index = 0; index < totalIndices; index += 3) {
  24016. indices[index] = index;
  24017. indices[index + 1] = index + 1;
  24018. indices[index + 2] = index + 2;
  24019. }
  24020. this.setIndices(indices);
  24021. // Updating vertex buffers
  24022. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24023. kind = kinds[kindIndex];
  24024. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24025. }
  24026. // Updating submeshes
  24027. this.releaseSubMeshes();
  24028. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24029. var previousOne = previousSubmeshes[submeshIndex];
  24030. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24031. }
  24032. this._unIndexed = true;
  24033. this.synchronizeInstances();
  24034. return this;
  24035. };
  24036. /**
  24037. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24038. * This method returns the Mesh.
  24039. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24040. */
  24041. Mesh.prototype.flipFaces = function (flipNormals) {
  24042. if (flipNormals === void 0) { flipNormals = false; }
  24043. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24044. var i;
  24045. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24046. for (i = 0; i < vertex_data.normals.length; i++) {
  24047. vertex_data.normals[i] *= -1;
  24048. }
  24049. }
  24050. if (vertex_data.indices) {
  24051. var temp;
  24052. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24053. // reassign indices
  24054. temp = vertex_data.indices[i + 1];
  24055. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24056. vertex_data.indices[i + 2] = temp;
  24057. }
  24058. }
  24059. vertex_data.applyToMesh(this);
  24060. return this;
  24061. };
  24062. // Instances
  24063. /**
  24064. * Creates a new InstancedMesh object from the mesh model.
  24065. * An instance shares the same properties and the same material than its model.
  24066. * Only these properties of each instance can then be set individually :
  24067. * - position
  24068. * - rotation
  24069. * - rotationQuaternion
  24070. * - setPivotMatrix
  24071. * - scaling
  24072. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24073. * Warning : this method is not supported for Line mesh and LineSystem
  24074. */
  24075. Mesh.prototype.createInstance = function (name) {
  24076. return new BABYLON.InstancedMesh(name, this);
  24077. };
  24078. /**
  24079. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24080. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24081. * This method returns the Mesh.
  24082. */
  24083. Mesh.prototype.synchronizeInstances = function () {
  24084. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24085. var instance = this.instances[instanceIndex];
  24086. instance._syncSubMeshes();
  24087. }
  24088. return this;
  24089. };
  24090. /**
  24091. * Simplify the mesh according to the given array of settings.
  24092. * Function will return immediately and will simplify async. It returns the Mesh.
  24093. * @param settings a collection of simplification settings.
  24094. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24095. * @param type the type of simplification to run.
  24096. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24097. */
  24098. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24099. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24100. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24101. this.getScene().simplificationQueue.addTask({
  24102. settings: settings,
  24103. parallelProcessing: parallelProcessing,
  24104. mesh: this,
  24105. simplificationType: simplificationType,
  24106. successCallback: successCallback
  24107. });
  24108. return this;
  24109. };
  24110. /**
  24111. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24112. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24113. * This should be used together with the simplification to avoid disappearing triangles.
  24114. * Returns the Mesh.
  24115. * @param successCallback an optional success callback to be called after the optimization finished.
  24116. */
  24117. Mesh.prototype.optimizeIndices = function (successCallback) {
  24118. var _this = this;
  24119. var indices = this.getIndices();
  24120. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24121. if (!positions || !indices) {
  24122. return this;
  24123. }
  24124. var vectorPositions = new Array();
  24125. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24126. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24127. }
  24128. var dupes = new Array();
  24129. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24130. var realPos = vectorPositions.length - 1 - iteration;
  24131. var testedPosition = vectorPositions[realPos];
  24132. for (var j = 0; j < realPos; ++j) {
  24133. var againstPosition = vectorPositions[j];
  24134. if (testedPosition.equals(againstPosition)) {
  24135. dupes[realPos] = j;
  24136. break;
  24137. }
  24138. }
  24139. }, function () {
  24140. for (var i = 0; i < indices.length; ++i) {
  24141. indices[i] = dupes[indices[i]] || indices[i];
  24142. }
  24143. //indices are now reordered
  24144. var originalSubMeshes = _this.subMeshes.slice(0);
  24145. _this.setIndices(indices);
  24146. _this.subMeshes = originalSubMeshes;
  24147. if (successCallback) {
  24148. successCallback(_this);
  24149. }
  24150. });
  24151. return this;
  24152. };
  24153. Mesh.prototype.serialize = function (serializationObject) {
  24154. serializationObject.name = this.name;
  24155. serializationObject.id = this.id;
  24156. serializationObject.type = this.getClassName();
  24157. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24158. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24159. }
  24160. serializationObject.position = this.position.asArray();
  24161. if (this.rotationQuaternion) {
  24162. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24163. }
  24164. else if (this.rotation) {
  24165. serializationObject.rotation = this.rotation.asArray();
  24166. }
  24167. serializationObject.scaling = this.scaling.asArray();
  24168. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24169. serializationObject.isEnabled = this.isEnabled();
  24170. serializationObject.isVisible = this.isVisible;
  24171. serializationObject.infiniteDistance = this.infiniteDistance;
  24172. serializationObject.pickable = this.isPickable;
  24173. serializationObject.receiveShadows = this.receiveShadows;
  24174. serializationObject.billboardMode = this.billboardMode;
  24175. serializationObject.visibility = this.visibility;
  24176. serializationObject.checkCollisions = this.checkCollisions;
  24177. serializationObject.isBlocker = this.isBlocker;
  24178. // Parent
  24179. if (this.parent) {
  24180. serializationObject.parentId = this.parent.id;
  24181. }
  24182. // Geometry
  24183. var geometry = this._geometry;
  24184. if (geometry) {
  24185. var geometryId = geometry.id;
  24186. serializationObject.geometryId = geometryId;
  24187. // SubMeshes
  24188. serializationObject.subMeshes = [];
  24189. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24190. var subMesh = this.subMeshes[subIndex];
  24191. serializationObject.subMeshes.push({
  24192. materialIndex: subMesh.materialIndex,
  24193. verticesStart: subMesh.verticesStart,
  24194. verticesCount: subMesh.verticesCount,
  24195. indexStart: subMesh.indexStart,
  24196. indexCount: subMesh.indexCount
  24197. });
  24198. }
  24199. }
  24200. // Material
  24201. if (this.material) {
  24202. serializationObject.materialId = this.material.id;
  24203. }
  24204. else {
  24205. this.material = null;
  24206. }
  24207. // Morph targets
  24208. if (this.morphTargetManager) {
  24209. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24210. }
  24211. // Skeleton
  24212. if (this.skeleton) {
  24213. serializationObject.skeletonId = this.skeleton.id;
  24214. }
  24215. // Physics
  24216. //TODO implement correct serialization for physics impostors.
  24217. var impostor = this.getPhysicsImpostor();
  24218. if (impostor) {
  24219. serializationObject.physicsMass = impostor.getParam("mass");
  24220. serializationObject.physicsFriction = impostor.getParam("friction");
  24221. serializationObject.physicsRestitution = impostor.getParam("mass");
  24222. serializationObject.physicsImpostor = impostor.type;
  24223. }
  24224. // Metadata
  24225. if (this.metadata) {
  24226. serializationObject.metadata = this.metadata;
  24227. }
  24228. // Instances
  24229. serializationObject.instances = [];
  24230. for (var index = 0; index < this.instances.length; index++) {
  24231. var instance = this.instances[index];
  24232. var serializationInstance = {
  24233. name: instance.name,
  24234. position: instance.position.asArray(),
  24235. scaling: instance.scaling.asArray()
  24236. };
  24237. if (instance.rotationQuaternion) {
  24238. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24239. }
  24240. else if (instance.rotation) {
  24241. serializationInstance.rotation = instance.rotation.asArray();
  24242. }
  24243. serializationObject.instances.push(serializationInstance);
  24244. // Animations
  24245. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24246. serializationInstance.ranges = instance.serializeAnimationRanges();
  24247. }
  24248. //
  24249. // Animations
  24250. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24251. serializationObject.ranges = this.serializeAnimationRanges();
  24252. // Layer mask
  24253. serializationObject.layerMask = this.layerMask;
  24254. // Alpha
  24255. serializationObject.alphaIndex = this.alphaIndex;
  24256. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24257. // Overlay
  24258. serializationObject.overlayAlpha = this.overlayAlpha;
  24259. serializationObject.overlayColor = this.overlayColor.asArray();
  24260. serializationObject.renderOverlay = this.renderOverlay;
  24261. // Fog
  24262. serializationObject.applyFog = this.applyFog;
  24263. // Action Manager
  24264. if (this.actionManager) {
  24265. serializationObject.actions = this.actionManager.serialize(this.name);
  24266. }
  24267. };
  24268. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24269. if (!this.geometry) {
  24270. return;
  24271. }
  24272. this._markSubMeshesAsAttributesDirty();
  24273. var morphTargetManager = this._morphTargetManager;
  24274. if (morphTargetManager && morphTargetManager.vertexCount) {
  24275. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24276. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24277. this.morphTargetManager = null;
  24278. return;
  24279. }
  24280. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24281. var morphTarget = morphTargetManager.getActiveTarget(index);
  24282. var positions = morphTarget.getPositions();
  24283. if (!positions) {
  24284. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24285. return;
  24286. }
  24287. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24288. var normals = morphTarget.getNormals();
  24289. if (normals) {
  24290. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24291. }
  24292. var tangents = morphTarget.getTangents();
  24293. if (tangents) {
  24294. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24295. }
  24296. }
  24297. }
  24298. else {
  24299. var index = 0;
  24300. // Positions
  24301. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24302. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24303. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24304. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24305. }
  24306. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24307. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24308. }
  24309. index++;
  24310. }
  24311. }
  24312. };
  24313. // Statics
  24314. /**
  24315. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24316. * The parameter `parsedMesh` is the mesh to be copied.
  24317. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24318. */
  24319. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24320. var mesh;
  24321. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24322. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24323. }
  24324. else {
  24325. mesh = new Mesh(parsedMesh.name, scene);
  24326. }
  24327. mesh.id = parsedMesh.id;
  24328. if (BABYLON.Tags) {
  24329. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24330. }
  24331. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24332. if (parsedMesh.metadata !== undefined) {
  24333. mesh.metadata = parsedMesh.metadata;
  24334. }
  24335. if (parsedMesh.rotationQuaternion) {
  24336. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24337. }
  24338. else if (parsedMesh.rotation) {
  24339. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24340. }
  24341. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24342. if (parsedMesh.localMatrix) {
  24343. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24344. }
  24345. else if (parsedMesh.pivotMatrix) {
  24346. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24347. }
  24348. mesh.setEnabled(parsedMesh.isEnabled);
  24349. mesh.isVisible = parsedMesh.isVisible;
  24350. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24351. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24352. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24353. if (parsedMesh.applyFog !== undefined) {
  24354. mesh.applyFog = parsedMesh.applyFog;
  24355. }
  24356. if (parsedMesh.pickable !== undefined) {
  24357. mesh.isPickable = parsedMesh.pickable;
  24358. }
  24359. if (parsedMesh.alphaIndex !== undefined) {
  24360. mesh.alphaIndex = parsedMesh.alphaIndex;
  24361. }
  24362. mesh.receiveShadows = parsedMesh.receiveShadows;
  24363. mesh.billboardMode = parsedMesh.billboardMode;
  24364. if (parsedMesh.visibility !== undefined) {
  24365. mesh.visibility = parsedMesh.visibility;
  24366. }
  24367. mesh.checkCollisions = parsedMesh.checkCollisions;
  24368. if (parsedMesh.isBlocker !== undefined) {
  24369. mesh.isBlocker = parsedMesh.isBlocker;
  24370. }
  24371. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24372. // freezeWorldMatrix
  24373. if (parsedMesh.freezeWorldMatrix) {
  24374. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24375. }
  24376. // Parent
  24377. if (parsedMesh.parentId) {
  24378. mesh._waitingParentId = parsedMesh.parentId;
  24379. }
  24380. // Actions
  24381. if (parsedMesh.actions !== undefined) {
  24382. mesh._waitingActions = parsedMesh.actions;
  24383. }
  24384. // Overlay
  24385. if (parsedMesh.overlayAlpha !== undefined) {
  24386. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24387. }
  24388. if (parsedMesh.overlayColor !== undefined) {
  24389. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24390. }
  24391. if (parsedMesh.renderOverlay !== undefined) {
  24392. mesh.renderOverlay = parsedMesh.renderOverlay;
  24393. }
  24394. // Geometry
  24395. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24396. if (parsedMesh.delayLoadingFile) {
  24397. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24398. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24399. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24400. if (parsedMesh._binaryInfo) {
  24401. mesh._binaryInfo = parsedMesh._binaryInfo;
  24402. }
  24403. mesh._delayInfo = [];
  24404. if (parsedMesh.hasUVs) {
  24405. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24406. }
  24407. if (parsedMesh.hasUVs2) {
  24408. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24409. }
  24410. if (parsedMesh.hasUVs3) {
  24411. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24412. }
  24413. if (parsedMesh.hasUVs4) {
  24414. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24415. }
  24416. if (parsedMesh.hasUVs5) {
  24417. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24418. }
  24419. if (parsedMesh.hasUVs6) {
  24420. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24421. }
  24422. if (parsedMesh.hasColors) {
  24423. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24424. }
  24425. if (parsedMesh.hasMatricesIndices) {
  24426. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24427. }
  24428. if (parsedMesh.hasMatricesWeights) {
  24429. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24430. }
  24431. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24432. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24433. mesh._checkDelayState();
  24434. }
  24435. }
  24436. else {
  24437. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24438. }
  24439. // Material
  24440. if (parsedMesh.materialId) {
  24441. mesh.setMaterialByID(parsedMesh.materialId);
  24442. }
  24443. else {
  24444. mesh.material = null;
  24445. }
  24446. // Morph targets
  24447. if (parsedMesh.morphTargetManagerId > -1) {
  24448. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24449. }
  24450. // Skeleton
  24451. if (parsedMesh.skeletonId > -1) {
  24452. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24453. if (parsedMesh.numBoneInfluencers) {
  24454. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24455. }
  24456. }
  24457. // Animations
  24458. if (parsedMesh.animations) {
  24459. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24460. var parsedAnimation = parsedMesh.animations[animationIndex];
  24461. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24462. }
  24463. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24464. }
  24465. if (parsedMesh.autoAnimate) {
  24466. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24467. }
  24468. // Layer Mask
  24469. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24470. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24471. }
  24472. else {
  24473. mesh.layerMask = 0x0FFFFFFF;
  24474. }
  24475. // Physics
  24476. if (parsedMesh.physicsImpostor) {
  24477. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24478. mass: parsedMesh.physicsMass,
  24479. friction: parsedMesh.physicsFriction,
  24480. restitution: parsedMesh.physicsRestitution
  24481. }, scene);
  24482. }
  24483. // Instances
  24484. if (parsedMesh.instances) {
  24485. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24486. var parsedInstance = parsedMesh.instances[index];
  24487. var instance = mesh.createInstance(parsedInstance.name);
  24488. if (BABYLON.Tags) {
  24489. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24490. }
  24491. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24492. if (parsedInstance.parentId) {
  24493. instance._waitingParentId = parsedInstance.parentId;
  24494. }
  24495. if (parsedInstance.rotationQuaternion) {
  24496. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24497. }
  24498. else if (parsedInstance.rotation) {
  24499. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24500. }
  24501. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24502. instance.checkCollisions = mesh.checkCollisions;
  24503. if (parsedMesh.animations) {
  24504. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24505. parsedAnimation = parsedMesh.animations[animationIndex];
  24506. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24507. }
  24508. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24509. }
  24510. }
  24511. }
  24512. return mesh;
  24513. };
  24514. /**
  24515. * Creates a ribbon mesh.
  24516. * Please consider using the same method from the MeshBuilder class instead.
  24517. * 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.
  24518. *
  24519. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24520. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24521. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24522. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24523. * 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.
  24524. * 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.
  24525. * 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
  24526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24527. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24529. */
  24530. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24531. if (closeArray === void 0) { closeArray = false; }
  24532. if (updatable === void 0) { updatable = false; }
  24533. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24534. pathArray: pathArray,
  24535. closeArray: closeArray,
  24536. closePath: closePath,
  24537. offset: offset,
  24538. updatable: updatable,
  24539. sideOrientation: sideOrientation,
  24540. instance: instance
  24541. }, scene);
  24542. };
  24543. /**
  24544. * Creates a plane polygonal mesh. By default, this is a disc.
  24545. * Please consider using the same method from the MeshBuilder class instead.
  24546. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24547. * 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.
  24548. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24551. */
  24552. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24553. if (scene === void 0) { scene = null; }
  24554. var options = {
  24555. radius: radius,
  24556. tessellation: tessellation,
  24557. sideOrientation: sideOrientation,
  24558. updatable: updatable
  24559. };
  24560. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24561. };
  24562. /**
  24563. * Creates a box mesh.
  24564. * Please consider using the same method from the MeshBuilder class instead.
  24565. * The parameter `size` sets the size (float) of each box side (default 1).
  24566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24567. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24569. */
  24570. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24571. if (scene === void 0) { scene = null; }
  24572. var options = {
  24573. size: size,
  24574. sideOrientation: sideOrientation,
  24575. updatable: updatable
  24576. };
  24577. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24578. };
  24579. /**
  24580. * Creates a sphere mesh.
  24581. * Please consider using the same method from the MeshBuilder class instead.
  24582. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24583. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24585. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24587. */
  24588. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24589. var options = {
  24590. segments: segments,
  24591. diameterX: diameter,
  24592. diameterY: diameter,
  24593. diameterZ: diameter,
  24594. sideOrientation: sideOrientation,
  24595. updatable: updatable
  24596. };
  24597. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24598. };
  24599. /**
  24600. * Creates a cylinder or a cone mesh.
  24601. * Please consider using the same method from the MeshBuilder class instead.
  24602. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24603. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24604. * 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.
  24605. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24606. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24608. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24610. */
  24611. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24612. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24613. if (scene !== undefined) {
  24614. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24615. updatable = scene;
  24616. }
  24617. scene = subdivisions;
  24618. subdivisions = 1;
  24619. }
  24620. var options = {
  24621. height: height,
  24622. diameterTop: diameterTop,
  24623. diameterBottom: diameterBottom,
  24624. tessellation: tessellation,
  24625. subdivisions: subdivisions,
  24626. sideOrientation: sideOrientation,
  24627. updatable: updatable
  24628. };
  24629. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24630. };
  24631. // Torus (Code from SharpDX.org)
  24632. /**
  24633. * Creates a torus mesh.
  24634. * Please consider using the same method from the MeshBuilder class instead.
  24635. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24636. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24637. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24641. */
  24642. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24643. var options = {
  24644. diameter: diameter,
  24645. thickness: thickness,
  24646. tessellation: tessellation,
  24647. sideOrientation: sideOrientation,
  24648. updatable: updatable
  24649. };
  24650. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24651. };
  24652. /**
  24653. * Creates a torus knot mesh.
  24654. * Please consider using the same method from the MeshBuilder class instead.
  24655. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24656. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24657. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24658. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24660. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24662. */
  24663. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24664. var options = {
  24665. radius: radius,
  24666. tube: tube,
  24667. radialSegments: radialSegments,
  24668. tubularSegments: tubularSegments,
  24669. p: p,
  24670. q: q,
  24671. sideOrientation: sideOrientation,
  24672. updatable: updatable
  24673. };
  24674. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24675. };
  24676. /**
  24677. * Creates a line mesh.
  24678. * Please consider using the same method from the MeshBuilder class instead.
  24679. * 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.
  24680. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24681. * The parameter `points` is an array successive Vector3.
  24682. * 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
  24683. * When updating an instance, remember that only point positions can change, not the number of points.
  24684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24685. */
  24686. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24687. if (scene === void 0) { scene = null; }
  24688. if (updatable === void 0) { updatable = false; }
  24689. if (instance === void 0) { instance = null; }
  24690. var options = {
  24691. points: points,
  24692. updatable: updatable,
  24693. instance: instance
  24694. };
  24695. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24696. };
  24697. /**
  24698. * Creates a dashed line mesh.
  24699. * Please consider using the same method from the MeshBuilder class instead.
  24700. * 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.
  24701. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24702. * The parameter `points` is an array successive Vector3.
  24703. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24704. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24705. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24706. * 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
  24707. * When updating an instance, remember that only point positions can change, not the number of points.
  24708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24709. */
  24710. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24711. if (scene === void 0) { scene = null; }
  24712. var options = {
  24713. points: points,
  24714. dashSize: dashSize,
  24715. gapSize: gapSize,
  24716. dashNb: dashNb,
  24717. updatable: updatable,
  24718. instance: instance
  24719. };
  24720. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24721. };
  24722. /**
  24723. * Creates a polygon mesh.
  24724. * Please consider using the same method from the MeshBuilder class instead.
  24725. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24726. * 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.
  24727. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24729. * Remember you can only change the shape positions, not their number when updating a polygon.
  24730. */
  24731. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24732. var options = {
  24733. shape: shape,
  24734. holes: holes,
  24735. updatable: updatable,
  24736. sideOrientation: sideOrientation
  24737. };
  24738. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24739. };
  24740. /**
  24741. * Creates an extruded polygon mesh, with depth in the Y direction.
  24742. * Please consider using the same method from the MeshBuilder class instead.
  24743. */
  24744. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24745. var options = {
  24746. shape: shape,
  24747. holes: holes,
  24748. depth: depth,
  24749. updatable: updatable,
  24750. sideOrientation: sideOrientation
  24751. };
  24752. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24753. };
  24754. /**
  24755. * Creates an extruded shape mesh.
  24756. * 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.
  24757. * Please consider using the same method from the MeshBuilder class instead.
  24758. *
  24759. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24760. * 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
  24761. * extruded along the Z axis.
  24762. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24763. * 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.
  24764. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24765. * 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
  24766. * 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
  24767. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24768. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24769. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24771. */
  24772. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24773. if (scene === void 0) { scene = null; }
  24774. var options = {
  24775. shape: shape,
  24776. path: path,
  24777. scale: scale,
  24778. rotation: rotation,
  24779. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24780. sideOrientation: sideOrientation,
  24781. instance: instance,
  24782. updatable: updatable
  24783. };
  24784. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24785. };
  24786. /**
  24787. * Creates an custom extruded shape mesh.
  24788. * 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.
  24789. * Please consider using the same method from the MeshBuilder class instead.
  24790. *
  24791. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24792. * 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
  24793. * extruded along the Z axis.
  24794. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24795. * 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
  24796. * and the distance of this point from the begining of the path :
  24797. * ```javascript
  24798. * var rotationFunction = function(i, distance) {
  24799. * // do things
  24800. * return rotationValue; }
  24801. * ```
  24802. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24803. * 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
  24804. * and the distance of this point from the begining of the path :
  24805. * ```javascript
  24806. * var scaleFunction = function(i, distance) {
  24807. * // do things
  24808. * return scaleValue;}
  24809. * ```
  24810. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24811. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24812. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24813. * 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
  24814. * 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
  24815. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24817. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24819. */
  24820. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24821. var options = {
  24822. shape: shape,
  24823. path: path,
  24824. scaleFunction: scaleFunction,
  24825. rotationFunction: rotationFunction,
  24826. ribbonCloseArray: ribbonCloseArray,
  24827. ribbonClosePath: ribbonClosePath,
  24828. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24829. sideOrientation: sideOrientation,
  24830. instance: instance,
  24831. updatable: updatable
  24832. };
  24833. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24834. };
  24835. /**
  24836. * Creates lathe mesh.
  24837. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24838. * Please consider using the same method from the MeshBuilder class instead.
  24839. * 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
  24840. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24841. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24842. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24846. */
  24847. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24848. var options = {
  24849. shape: shape,
  24850. radius: radius,
  24851. tessellation: tessellation,
  24852. sideOrientation: sideOrientation,
  24853. updatable: updatable
  24854. };
  24855. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24856. };
  24857. /**
  24858. * Creates a plane mesh.
  24859. * Please consider using the same method from the MeshBuilder class instead.
  24860. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24861. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24862. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24864. */
  24865. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24866. var options = {
  24867. size: size,
  24868. width: size,
  24869. height: size,
  24870. sideOrientation: sideOrientation,
  24871. updatable: updatable
  24872. };
  24873. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24874. };
  24875. /**
  24876. * Creates a ground mesh.
  24877. * Please consider using the same method from the MeshBuilder class instead.
  24878. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24879. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24881. */
  24882. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24883. var options = {
  24884. width: width,
  24885. height: height,
  24886. subdivisions: subdivisions,
  24887. updatable: updatable
  24888. };
  24889. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24890. };
  24891. /**
  24892. * Creates a tiled ground mesh.
  24893. * Please consider using the same method from the MeshBuilder class instead.
  24894. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24895. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24896. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24897. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24898. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24899. * numbers of subdivisions on the ground width and height of each tile.
  24900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24901. */
  24902. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24903. var options = {
  24904. xmin: xmin,
  24905. zmin: zmin,
  24906. xmax: xmax,
  24907. zmax: zmax,
  24908. subdivisions: subdivisions,
  24909. precision: precision,
  24910. updatable: updatable
  24911. };
  24912. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24913. };
  24914. /**
  24915. * Creates a ground mesh from a height map.
  24916. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24917. * Please consider using the same method from the MeshBuilder class instead.
  24918. * The parameter `url` sets the URL of the height map image resource.
  24919. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24920. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24921. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24922. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24923. * 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).
  24924. * This function is passed the newly built mesh :
  24925. * ```javascript
  24926. * function(mesh) { // do things
  24927. * return; }
  24928. * ```
  24929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24930. */
  24931. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24932. var options = {
  24933. width: width,
  24934. height: height,
  24935. subdivisions: subdivisions,
  24936. minHeight: minHeight,
  24937. maxHeight: maxHeight,
  24938. updatable: updatable,
  24939. onReady: onReady
  24940. };
  24941. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24942. };
  24943. /**
  24944. * Creates a tube mesh.
  24945. * 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.
  24946. * Please consider using the same method from the MeshBuilder class instead.
  24947. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24948. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24949. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24950. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24951. * 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.
  24952. * It must return a radius value (positive float) :
  24953. * ```javascript
  24954. * var radiusFunction = function(i, distance) {
  24955. * // do things
  24956. * return radius; }
  24957. * ```
  24958. * 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
  24959. * 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
  24960. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24961. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24963. */
  24964. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24965. var options = {
  24966. path: path,
  24967. radius: radius,
  24968. tessellation: tessellation,
  24969. radiusFunction: radiusFunction,
  24970. arc: 1,
  24971. cap: cap,
  24972. updatable: updatable,
  24973. sideOrientation: sideOrientation,
  24974. instance: instance
  24975. };
  24976. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24977. };
  24978. /**
  24979. * Creates a polyhedron mesh.
  24980. * Please consider using the same method from the MeshBuilder class instead.
  24981. * 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
  24982. * to choose the wanted type.
  24983. * The parameter `size` (positive float, default 1) sets the polygon size.
  24984. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24985. * 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`.
  24986. * 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
  24987. * 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)`).
  24988. * 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
  24989. * 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.
  24990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24993. */
  24994. Mesh.CreatePolyhedron = function (name, options, scene) {
  24995. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24996. };
  24997. /**
  24998. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24999. * Please consider using the same method from the MeshBuilder class instead.
  25000. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25001. * 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`).
  25002. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25003. * 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.
  25004. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25007. */
  25008. Mesh.CreateIcoSphere = function (name, options, scene) {
  25009. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25010. };
  25011. /**
  25012. * Creates a decal mesh.
  25013. * Please consider using the same method from the MeshBuilder class instead.
  25014. * 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.
  25015. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25016. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25017. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25018. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25019. */
  25020. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25021. var options = {
  25022. position: position,
  25023. normal: normal,
  25024. size: size,
  25025. angle: angle
  25026. };
  25027. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25028. };
  25029. // Skeletons
  25030. /**
  25031. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25032. */
  25033. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25034. if (!this._sourcePositions) {
  25035. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25036. if (!source) {
  25037. return this._sourcePositions;
  25038. }
  25039. this._sourcePositions = new Float32Array(source);
  25040. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25041. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25042. }
  25043. }
  25044. return this._sourcePositions;
  25045. };
  25046. /**
  25047. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25048. */
  25049. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25050. if (!this._sourceNormals) {
  25051. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25052. if (!source) {
  25053. return this._sourceNormals;
  25054. }
  25055. this._sourceNormals = new Float32Array(source);
  25056. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25057. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25058. }
  25059. }
  25060. return this._sourceNormals;
  25061. };
  25062. /**
  25063. * Updates the vertex buffer by applying transformation from the bones.
  25064. * Returns the Mesh.
  25065. *
  25066. * @param {skeleton} skeleton to apply
  25067. */
  25068. Mesh.prototype.applySkeleton = function (skeleton) {
  25069. if (!this.geometry) {
  25070. return this;
  25071. }
  25072. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25073. return this;
  25074. }
  25075. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25076. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25077. return this;
  25078. }
  25079. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25080. return this;
  25081. }
  25082. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25083. return this;
  25084. }
  25085. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25086. return this;
  25087. }
  25088. if (!this._sourcePositions) {
  25089. var submeshes = this.subMeshes.slice();
  25090. this.setPositionsForCPUSkinning();
  25091. this.subMeshes = submeshes;
  25092. }
  25093. if (!this._sourceNormals) {
  25094. this.setNormalsForCPUSkinning();
  25095. }
  25096. // positionsData checks for not being Float32Array will only pass at most once
  25097. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25098. if (!positionsData) {
  25099. return this;
  25100. }
  25101. if (!(positionsData instanceof Float32Array)) {
  25102. positionsData = new Float32Array(positionsData);
  25103. }
  25104. // normalsData checks for not being Float32Array will only pass at most once
  25105. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25106. if (!normalsData) {
  25107. return this;
  25108. }
  25109. if (!(normalsData instanceof Float32Array)) {
  25110. normalsData = new Float32Array(normalsData);
  25111. }
  25112. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25113. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25114. if (!matricesWeightsData || !matricesIndicesData) {
  25115. return this;
  25116. }
  25117. var needExtras = this.numBoneInfluencers > 4;
  25118. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25119. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25120. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25121. return this;
  25122. }
  25123. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25124. var tempVector3 = BABYLON.Vector3.Zero();
  25125. var finalMatrix = new BABYLON.Matrix();
  25126. var tempMatrix = new BABYLON.Matrix();
  25127. var matWeightIdx = 0;
  25128. var inf;
  25129. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25130. var weight;
  25131. for (inf = 0; inf < 4; inf++) {
  25132. weight = matricesWeightsData[matWeightIdx + inf];
  25133. if (weight > 0) {
  25134. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25135. finalMatrix.addToSelf(tempMatrix);
  25136. }
  25137. else
  25138. break;
  25139. }
  25140. if (needExtras) {
  25141. for (inf = 0; inf < 4; inf++) {
  25142. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25143. if (weight > 0) {
  25144. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25145. finalMatrix.addToSelf(tempMatrix);
  25146. }
  25147. else
  25148. break;
  25149. }
  25150. }
  25151. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25152. tempVector3.toArray(positionsData, index);
  25153. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25154. tempVector3.toArray(normalsData, index);
  25155. finalMatrix.reset();
  25156. }
  25157. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25158. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25159. return this;
  25160. };
  25161. // Tools
  25162. /**
  25163. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25164. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25165. */
  25166. Mesh.MinMax = function (meshes) {
  25167. var minVector = null;
  25168. var maxVector = null;
  25169. meshes.forEach(function (mesh, index, array) {
  25170. var boundingInfo = mesh.getBoundingInfo();
  25171. if (!boundingInfo) {
  25172. return;
  25173. }
  25174. var boundingBox = boundingInfo.boundingBox;
  25175. if (!minVector || !maxVector) {
  25176. minVector = boundingBox.minimumWorld;
  25177. maxVector = boundingBox.maximumWorld;
  25178. }
  25179. else {
  25180. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25181. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25182. }
  25183. });
  25184. if (!minVector || !maxVector) {
  25185. return {
  25186. min: BABYLON.Vector3.Zero(),
  25187. max: BABYLON.Vector3.Zero()
  25188. };
  25189. }
  25190. return {
  25191. min: minVector,
  25192. max: maxVector
  25193. };
  25194. };
  25195. /**
  25196. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25197. */
  25198. Mesh.Center = function (meshesOrMinMaxVector) {
  25199. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25200. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25201. };
  25202. /**
  25203. * Merge the array of meshes into a single mesh for performance reasons.
  25204. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25205. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25206. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25207. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25208. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25209. */
  25210. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25211. if (disposeSource === void 0) { disposeSource = true; }
  25212. var index;
  25213. if (!allow32BitsIndices) {
  25214. var totalVertices = 0;
  25215. // Counting vertices
  25216. for (index = 0; index < meshes.length; index++) {
  25217. if (meshes[index]) {
  25218. totalVertices += meshes[index].getTotalVertices();
  25219. if (totalVertices > 65536) {
  25220. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25221. return null;
  25222. }
  25223. }
  25224. }
  25225. }
  25226. // Merge
  25227. var vertexData = null;
  25228. var otherVertexData;
  25229. var indiceArray = new Array();
  25230. var source = null;
  25231. for (index = 0; index < meshes.length; index++) {
  25232. if (meshes[index]) {
  25233. meshes[index].computeWorldMatrix(true);
  25234. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25235. otherVertexData.transform(meshes[index].getWorldMatrix());
  25236. if (vertexData) {
  25237. vertexData.merge(otherVertexData);
  25238. }
  25239. else {
  25240. vertexData = otherVertexData;
  25241. source = meshes[index];
  25242. }
  25243. if (subdivideWithSubMeshes) {
  25244. indiceArray.push(meshes[index].getTotalIndices());
  25245. }
  25246. }
  25247. }
  25248. source = source;
  25249. if (!meshSubclass) {
  25250. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25251. }
  25252. vertexData.applyToMesh(meshSubclass);
  25253. // Setting properties
  25254. meshSubclass.material = source.material;
  25255. meshSubclass.checkCollisions = source.checkCollisions;
  25256. // Cleaning
  25257. if (disposeSource) {
  25258. for (index = 0; index < meshes.length; index++) {
  25259. if (meshes[index]) {
  25260. meshes[index].dispose();
  25261. }
  25262. }
  25263. }
  25264. // Subdivide
  25265. if (subdivideWithSubMeshes) {
  25266. //-- Suppresions du submesh global
  25267. meshSubclass.releaseSubMeshes();
  25268. index = 0;
  25269. var offset = 0;
  25270. //-- aplique la subdivision en fonction du tableau d'indices
  25271. while (index < indiceArray.length) {
  25272. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25273. offset += indiceArray[index];
  25274. index++;
  25275. }
  25276. }
  25277. return meshSubclass;
  25278. };
  25279. // Consts
  25280. Mesh._FRONTSIDE = 0;
  25281. Mesh._BACKSIDE = 1;
  25282. Mesh._DOUBLESIDE = 2;
  25283. Mesh._DEFAULTSIDE = 0;
  25284. Mesh._NO_CAP = 0;
  25285. Mesh._CAP_START = 1;
  25286. Mesh._CAP_END = 2;
  25287. Mesh._CAP_ALL = 3;
  25288. return Mesh;
  25289. }(BABYLON.AbstractMesh));
  25290. BABYLON.Mesh = Mesh;
  25291. })(BABYLON || (BABYLON = {}));
  25292. //# sourceMappingURL=babylon.mesh.js.map
  25293. var BABYLON;
  25294. (function (BABYLON) {
  25295. var BaseSubMesh = /** @class */ (function () {
  25296. function BaseSubMesh() {
  25297. }
  25298. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25299. get: function () {
  25300. return this._materialEffect;
  25301. },
  25302. enumerable: true,
  25303. configurable: true
  25304. });
  25305. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25306. if (defines === void 0) { defines = null; }
  25307. if (this._materialEffect === effect) {
  25308. if (!effect) {
  25309. this._materialDefines = null;
  25310. }
  25311. return;
  25312. }
  25313. this._materialDefines = defines;
  25314. this._materialEffect = effect;
  25315. };
  25316. return BaseSubMesh;
  25317. }());
  25318. BABYLON.BaseSubMesh = BaseSubMesh;
  25319. var SubMesh = /** @class */ (function (_super) {
  25320. __extends(SubMesh, _super);
  25321. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25322. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25323. var _this = _super.call(this) || this;
  25324. _this.materialIndex = materialIndex;
  25325. _this.verticesStart = verticesStart;
  25326. _this.verticesCount = verticesCount;
  25327. _this.indexStart = indexStart;
  25328. _this.indexCount = indexCount;
  25329. _this._renderId = 0;
  25330. _this._mesh = mesh;
  25331. _this._renderingMesh = renderingMesh || mesh;
  25332. mesh.subMeshes.push(_this);
  25333. _this._trianglePlanes = [];
  25334. _this._id = mesh.subMeshes.length - 1;
  25335. if (createBoundingBox) {
  25336. _this.refreshBoundingInfo();
  25337. mesh.computeWorldMatrix(true);
  25338. }
  25339. return _this;
  25340. }
  25341. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25342. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25343. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25344. };
  25345. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25346. get: function () {
  25347. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25348. },
  25349. enumerable: true,
  25350. configurable: true
  25351. });
  25352. /**
  25353. * Returns the submesh BoudingInfo object.
  25354. */
  25355. SubMesh.prototype.getBoundingInfo = function () {
  25356. if (this.IsGlobal) {
  25357. return this._mesh.getBoundingInfo();
  25358. }
  25359. return this._boundingInfo;
  25360. };
  25361. /**
  25362. * Sets the submesh BoundingInfo.
  25363. * Return the SubMesh.
  25364. */
  25365. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25366. this._boundingInfo = boundingInfo;
  25367. return this;
  25368. };
  25369. /**
  25370. * Returns the mesh of the current submesh.
  25371. */
  25372. SubMesh.prototype.getMesh = function () {
  25373. return this._mesh;
  25374. };
  25375. /**
  25376. * Returns the rendering mesh of the submesh.
  25377. */
  25378. SubMesh.prototype.getRenderingMesh = function () {
  25379. return this._renderingMesh;
  25380. };
  25381. /**
  25382. * Returns the submesh material.
  25383. */
  25384. SubMesh.prototype.getMaterial = function () {
  25385. var rootMaterial = this._renderingMesh.material;
  25386. if (rootMaterial && rootMaterial.getSubMaterial) {
  25387. var multiMaterial = rootMaterial;
  25388. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25389. if (this._currentMaterial !== effectiveMaterial) {
  25390. this._currentMaterial = effectiveMaterial;
  25391. this._materialDefines = null;
  25392. }
  25393. return effectiveMaterial;
  25394. }
  25395. if (!rootMaterial) {
  25396. return this._mesh.getScene().defaultMaterial;
  25397. }
  25398. return rootMaterial;
  25399. };
  25400. // Methods
  25401. /**
  25402. * Sets a new updated BoundingInfo object to the submesh.
  25403. * Returns the SubMesh.
  25404. */
  25405. SubMesh.prototype.refreshBoundingInfo = function () {
  25406. this._lastColliderWorldVertices = null;
  25407. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25408. return this;
  25409. }
  25410. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25411. if (!data) {
  25412. this._boundingInfo = this._mesh._boundingInfo;
  25413. return this;
  25414. }
  25415. var indices = this._renderingMesh.getIndices();
  25416. var extend;
  25417. //is this the only submesh?
  25418. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25419. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25420. if (!boundingInfo) {
  25421. return this;
  25422. }
  25423. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25424. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25425. }
  25426. else {
  25427. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25428. }
  25429. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25430. return this;
  25431. };
  25432. SubMesh.prototype._checkCollision = function (collider) {
  25433. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25434. if (!boundingInfo) {
  25435. return false;
  25436. }
  25437. return boundingInfo._checkCollision(collider);
  25438. };
  25439. /**
  25440. * Updates the submesh BoundingInfo.
  25441. * Returns the Submesh.
  25442. */
  25443. SubMesh.prototype.updateBoundingInfo = function (world) {
  25444. var boundingInfo = this.getBoundingInfo();
  25445. if (!boundingInfo) {
  25446. this.refreshBoundingInfo();
  25447. boundingInfo = this.getBoundingInfo();
  25448. }
  25449. boundingInfo.update(world);
  25450. return this;
  25451. };
  25452. /**
  25453. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25454. * Boolean returned.
  25455. */
  25456. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25457. var boundingInfo = this.getBoundingInfo();
  25458. if (!boundingInfo) {
  25459. return false;
  25460. }
  25461. return boundingInfo.isInFrustum(frustumPlanes);
  25462. };
  25463. /**
  25464. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25465. * Boolean returned.
  25466. */
  25467. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25468. var boundingInfo = this.getBoundingInfo();
  25469. if (!boundingInfo) {
  25470. return false;
  25471. }
  25472. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25473. };
  25474. /**
  25475. * Renders the submesh.
  25476. * Returns it.
  25477. */
  25478. SubMesh.prototype.render = function (enableAlphaMode) {
  25479. this._renderingMesh.render(this, enableAlphaMode);
  25480. return this;
  25481. };
  25482. /**
  25483. * Returns a new Index Buffer.
  25484. * Type returned : WebGLBuffer.
  25485. */
  25486. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25487. if (!this._linesIndexBuffer) {
  25488. var linesIndices = [];
  25489. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25490. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25491. }
  25492. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25493. this.linesIndexCount = linesIndices.length;
  25494. }
  25495. return this._linesIndexBuffer;
  25496. };
  25497. /**
  25498. * True is the passed Ray intersects the submesh bounding box.
  25499. * Boolean returned.
  25500. */
  25501. SubMesh.prototype.canIntersects = function (ray) {
  25502. var boundingInfo = this.getBoundingInfo();
  25503. if (!boundingInfo) {
  25504. return false;
  25505. }
  25506. return ray.intersectsBox(boundingInfo.boundingBox);
  25507. };
  25508. /**
  25509. * Returns an object IntersectionInfo.
  25510. */
  25511. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25512. var intersectInfo = null;
  25513. // LineMesh first as it's also a Mesh...
  25514. if (this._mesh instanceof BABYLON.LinesMesh) {
  25515. var lineMesh = this._mesh;
  25516. // Line test
  25517. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25518. var p0 = positions[indices[index]];
  25519. var p1 = positions[indices[index + 1]];
  25520. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25521. if (length < 0) {
  25522. continue;
  25523. }
  25524. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25525. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25526. if (fastCheck) {
  25527. break;
  25528. }
  25529. }
  25530. }
  25531. }
  25532. else {
  25533. // Triangles test
  25534. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25535. var p0 = positions[indices[index]];
  25536. var p1 = positions[indices[index + 1]];
  25537. var p2 = positions[indices[index + 2]];
  25538. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25539. if (currentIntersectInfo) {
  25540. if (currentIntersectInfo.distance < 0) {
  25541. continue;
  25542. }
  25543. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25544. intersectInfo = currentIntersectInfo;
  25545. intersectInfo.faceId = index / 3;
  25546. if (fastCheck) {
  25547. break;
  25548. }
  25549. }
  25550. }
  25551. }
  25552. }
  25553. return intersectInfo;
  25554. };
  25555. SubMesh.prototype._rebuild = function () {
  25556. if (this._linesIndexBuffer) {
  25557. this._linesIndexBuffer = null;
  25558. }
  25559. };
  25560. // Clone
  25561. /**
  25562. * Creates a new Submesh from the passed Mesh.
  25563. */
  25564. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25565. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25566. if (!this.IsGlobal) {
  25567. var boundingInfo = this.getBoundingInfo();
  25568. if (!boundingInfo) {
  25569. return result;
  25570. }
  25571. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25572. }
  25573. return result;
  25574. };
  25575. // Dispose
  25576. /**
  25577. * Disposes the Submesh.
  25578. * Returns nothing.
  25579. */
  25580. SubMesh.prototype.dispose = function () {
  25581. if (this._linesIndexBuffer) {
  25582. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25583. this._linesIndexBuffer = null;
  25584. }
  25585. // Remove from mesh
  25586. var index = this._mesh.subMeshes.indexOf(this);
  25587. this._mesh.subMeshes.splice(index, 1);
  25588. };
  25589. // Statics
  25590. /**
  25591. * Creates a new Submesh from the passed parameters :
  25592. * - materialIndex (integer) : the index of the main mesh material.
  25593. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25594. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25595. * - mesh (Mesh) : the main mesh to create the submesh from.
  25596. * - renderingMesh (optional Mesh) : rendering mesh.
  25597. */
  25598. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25599. var minVertexIndex = Number.MAX_VALUE;
  25600. var maxVertexIndex = -Number.MAX_VALUE;
  25601. renderingMesh = (renderingMesh || mesh);
  25602. var indices = renderingMesh.getIndices();
  25603. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25604. var vertexIndex = indices[index];
  25605. if (vertexIndex < minVertexIndex)
  25606. minVertexIndex = vertexIndex;
  25607. if (vertexIndex > maxVertexIndex)
  25608. maxVertexIndex = vertexIndex;
  25609. }
  25610. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25611. };
  25612. return SubMesh;
  25613. }(BaseSubMesh));
  25614. BABYLON.SubMesh = SubMesh;
  25615. })(BABYLON || (BABYLON = {}));
  25616. //# sourceMappingURL=babylon.subMesh.js.map
  25617. var BABYLON;
  25618. (function (BABYLON) {
  25619. var EffectFallbacks = /** @class */ (function () {
  25620. function EffectFallbacks() {
  25621. this._defines = {};
  25622. this._currentRank = 32;
  25623. this._maxRank = -1;
  25624. }
  25625. EffectFallbacks.prototype.unBindMesh = function () {
  25626. this._mesh = null;
  25627. };
  25628. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25629. if (!this._defines[rank]) {
  25630. if (rank < this._currentRank) {
  25631. this._currentRank = rank;
  25632. }
  25633. if (rank > this._maxRank) {
  25634. this._maxRank = rank;
  25635. }
  25636. this._defines[rank] = new Array();
  25637. }
  25638. this._defines[rank].push(define);
  25639. };
  25640. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25641. this._meshRank = rank;
  25642. this._mesh = mesh;
  25643. if (rank < this._currentRank) {
  25644. this._currentRank = rank;
  25645. }
  25646. if (rank > this._maxRank) {
  25647. this._maxRank = rank;
  25648. }
  25649. };
  25650. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25651. get: function () {
  25652. return this._currentRank <= this._maxRank;
  25653. },
  25654. enumerable: true,
  25655. configurable: true
  25656. });
  25657. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25658. // First we try to switch to CPU skinning
  25659. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25660. this._mesh.computeBonesUsingShaders = false;
  25661. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25662. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25663. var scene = this._mesh.getScene();
  25664. for (var index = 0; index < scene.meshes.length; index++) {
  25665. var otherMesh = scene.meshes[index];
  25666. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25667. otherMesh.computeBonesUsingShaders = false;
  25668. }
  25669. }
  25670. }
  25671. else {
  25672. var currentFallbacks = this._defines[this._currentRank];
  25673. if (currentFallbacks) {
  25674. for (var index = 0; index < currentFallbacks.length; index++) {
  25675. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25676. }
  25677. }
  25678. this._currentRank++;
  25679. }
  25680. return currentDefines;
  25681. };
  25682. return EffectFallbacks;
  25683. }());
  25684. BABYLON.EffectFallbacks = EffectFallbacks;
  25685. var EffectCreationOptions = /** @class */ (function () {
  25686. function EffectCreationOptions() {
  25687. }
  25688. return EffectCreationOptions;
  25689. }());
  25690. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25691. var Effect = /** @class */ (function () {
  25692. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25693. if (samplers === void 0) { samplers = null; }
  25694. if (defines === void 0) { defines = null; }
  25695. if (fallbacks === void 0) { fallbacks = null; }
  25696. if (onCompiled === void 0) { onCompiled = null; }
  25697. if (onError === void 0) { onError = null; }
  25698. var _this = this;
  25699. this.uniqueId = 0;
  25700. this.onCompileObservable = new BABYLON.Observable();
  25701. this.onErrorObservable = new BABYLON.Observable();
  25702. this.onBindObservable = new BABYLON.Observable();
  25703. this._uniformBuffersNames = {};
  25704. this._isReady = false;
  25705. this._compilationError = "";
  25706. this.name = baseName;
  25707. if (attributesNamesOrOptions.attributes) {
  25708. var options = attributesNamesOrOptions;
  25709. this._engine = uniformsNamesOrEngine;
  25710. this._attributesNames = options.attributes;
  25711. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25712. this._samplers = options.samplers;
  25713. this.defines = options.defines;
  25714. this.onError = options.onError;
  25715. this.onCompiled = options.onCompiled;
  25716. this._fallbacks = options.fallbacks;
  25717. this._indexParameters = options.indexParameters;
  25718. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  25719. if (options.uniformBuffersNames) {
  25720. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25721. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25722. }
  25723. }
  25724. }
  25725. else {
  25726. this._engine = engine;
  25727. this.defines = defines;
  25728. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25729. this._samplers = samplers;
  25730. this._attributesNames = attributesNamesOrOptions;
  25731. this.onError = onError;
  25732. this.onCompiled = onCompiled;
  25733. this._indexParameters = indexParameters;
  25734. this._fallbacks = fallbacks;
  25735. }
  25736. this.uniqueId = Effect._uniqueIdSeed++;
  25737. var vertexSource;
  25738. var fragmentSource;
  25739. if (baseName.vertexElement) {
  25740. vertexSource = document.getElementById(baseName.vertexElement);
  25741. if (!vertexSource) {
  25742. vertexSource = baseName.vertexElement;
  25743. }
  25744. }
  25745. else {
  25746. vertexSource = baseName.vertex || baseName;
  25747. }
  25748. if (baseName.fragmentElement) {
  25749. fragmentSource = document.getElementById(baseName.fragmentElement);
  25750. if (!fragmentSource) {
  25751. fragmentSource = baseName.fragmentElement;
  25752. }
  25753. }
  25754. else {
  25755. fragmentSource = baseName.fragment || baseName;
  25756. }
  25757. this._loadVertexShader(vertexSource, function (vertexCode) {
  25758. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25759. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25760. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25761. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25762. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25763. if (baseName) {
  25764. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25765. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25766. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25767. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25768. }
  25769. else {
  25770. _this._vertexSourceCode = migratedVertexCode;
  25771. _this._fragmentSourceCode = migratedFragmentCode;
  25772. }
  25773. _this._prepareEffect();
  25774. });
  25775. });
  25776. });
  25777. });
  25778. });
  25779. });
  25780. }
  25781. Object.defineProperty(Effect.prototype, "key", {
  25782. get: function () {
  25783. return this._key;
  25784. },
  25785. enumerable: true,
  25786. configurable: true
  25787. });
  25788. // Properties
  25789. Effect.prototype.isReady = function () {
  25790. return this._isReady;
  25791. };
  25792. Effect.prototype.getEngine = function () {
  25793. return this._engine;
  25794. };
  25795. Effect.prototype.getProgram = function () {
  25796. return this._program;
  25797. };
  25798. Effect.prototype.getAttributesNames = function () {
  25799. return this._attributesNames;
  25800. };
  25801. Effect.prototype.getAttributeLocation = function (index) {
  25802. return this._attributes[index];
  25803. };
  25804. Effect.prototype.getAttributeLocationByName = function (name) {
  25805. var index = this._attributesNames.indexOf(name);
  25806. return this._attributes[index];
  25807. };
  25808. Effect.prototype.getAttributesCount = function () {
  25809. return this._attributes.length;
  25810. };
  25811. Effect.prototype.getUniformIndex = function (uniformName) {
  25812. return this._uniformsNames.indexOf(uniformName);
  25813. };
  25814. Effect.prototype.getUniform = function (uniformName) {
  25815. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25816. };
  25817. Effect.prototype.getSamplers = function () {
  25818. return this._samplers;
  25819. };
  25820. Effect.prototype.getCompilationError = function () {
  25821. return this._compilationError;
  25822. };
  25823. // Methods
  25824. Effect.prototype.executeWhenCompiled = function (func) {
  25825. if (this.isReady()) {
  25826. func(this);
  25827. return;
  25828. }
  25829. this.onCompileObservable.add(function (effect) {
  25830. func(effect);
  25831. });
  25832. };
  25833. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25834. if (BABYLON.Tools.IsWindowObjectExist()) {
  25835. // DOM element ?
  25836. if (vertex instanceof HTMLElement) {
  25837. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25838. callback(vertexCode);
  25839. return;
  25840. }
  25841. }
  25842. // Base64 encoded ?
  25843. if (vertex.substr(0, 7) === "base64:") {
  25844. var vertexBinary = window.atob(vertex.substr(7));
  25845. callback(vertexBinary);
  25846. return;
  25847. }
  25848. // Is in local store ?
  25849. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25850. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25851. return;
  25852. }
  25853. var vertexShaderUrl;
  25854. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25855. vertexShaderUrl = vertex;
  25856. }
  25857. else {
  25858. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25859. }
  25860. // Vertex shader
  25861. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25862. };
  25863. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25864. if (BABYLON.Tools.IsWindowObjectExist()) {
  25865. // DOM element ?
  25866. if (fragment instanceof HTMLElement) {
  25867. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25868. callback(fragmentCode);
  25869. return;
  25870. }
  25871. }
  25872. // Base64 encoded ?
  25873. if (fragment.substr(0, 7) === "base64:") {
  25874. var fragmentBinary = window.atob(fragment.substr(7));
  25875. callback(fragmentBinary);
  25876. return;
  25877. }
  25878. // Is in local store ?
  25879. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25880. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25881. return;
  25882. }
  25883. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25884. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25885. return;
  25886. }
  25887. var fragmentShaderUrl;
  25888. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25889. fragmentShaderUrl = fragment;
  25890. }
  25891. else {
  25892. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25893. }
  25894. // Fragment shader
  25895. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25896. };
  25897. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25898. // Rebuild shaders source code
  25899. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25900. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25901. vertexCode = prefix + vertexCode;
  25902. fragmentCode = prefix + fragmentCode;
  25903. // Number lines of shaders source code
  25904. var i = 2;
  25905. var regex = /\n/gm;
  25906. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25907. i = 2;
  25908. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25909. // Dump shaders name and formatted source code
  25910. if (this.name.vertexElement) {
  25911. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25912. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25913. }
  25914. else if (this.name.vertex) {
  25915. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25916. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25917. }
  25918. else {
  25919. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25920. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25921. }
  25922. };
  25923. ;
  25924. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25925. var preparedSourceCode = this._processPrecision(sourceCode);
  25926. if (this._engine.webGLVersion == 1) {
  25927. callback(preparedSourceCode);
  25928. return;
  25929. }
  25930. // Already converted
  25931. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25932. callback(preparedSourceCode.replace("#version 300 es", ""));
  25933. return;
  25934. }
  25935. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25936. // Remove extensions
  25937. // #extension GL_OES_standard_derivatives : enable
  25938. // #extension GL_EXT_shader_texture_lod : enable
  25939. // #extension GL_EXT_frag_depth : enable
  25940. // #extension GL_EXT_draw_buffers : require
  25941. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25942. var result = preparedSourceCode.replace(regex, "");
  25943. // Migrate to GLSL v300
  25944. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25945. result = result.replace(/attribute[ \t]/g, "in ");
  25946. result = result.replace(/[ \t]attribute/g, " in");
  25947. if (isFragment) {
  25948. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25949. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25950. result = result.replace(/texture2D\s*\(/g, "texture(");
  25951. result = result.replace(/textureCube\s*\(/g, "texture(");
  25952. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25953. result = result.replace(/gl_FragColor/g, "glFragColor");
  25954. result = result.replace(/gl_FragData/g, "glFragData");
  25955. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25956. }
  25957. callback(result);
  25958. };
  25959. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25960. var _this = this;
  25961. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25962. var match = regex.exec(sourceCode);
  25963. var returnValue = new String(sourceCode);
  25964. while (match != null) {
  25965. var includeFile = match[1];
  25966. // Uniform declaration
  25967. if (includeFile.indexOf("__decl__") !== -1) {
  25968. includeFile = includeFile.replace(/__decl__/, "");
  25969. if (this._engine.supportsUniformBuffers) {
  25970. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25971. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25972. }
  25973. includeFile = includeFile + "Declaration";
  25974. }
  25975. if (Effect.IncludesShadersStore[includeFile]) {
  25976. // Substitution
  25977. var includeContent = Effect.IncludesShadersStore[includeFile];
  25978. if (match[2]) {
  25979. var splits = match[3].split(",");
  25980. for (var index = 0; index < splits.length; index += 2) {
  25981. var source = new RegExp(splits[index], "g");
  25982. var dest = splits[index + 1];
  25983. includeContent = includeContent.replace(source, dest);
  25984. }
  25985. }
  25986. if (match[4]) {
  25987. var indexString = match[5];
  25988. if (indexString.indexOf("..") !== -1) {
  25989. var indexSplits = indexString.split("..");
  25990. var minIndex = parseInt(indexSplits[0]);
  25991. var maxIndex = parseInt(indexSplits[1]);
  25992. var sourceIncludeContent = includeContent.slice(0);
  25993. includeContent = "";
  25994. if (isNaN(maxIndex)) {
  25995. maxIndex = this._indexParameters[indexSplits[1]];
  25996. }
  25997. for (var i = minIndex; i < maxIndex; i++) {
  25998. if (!this._engine.supportsUniformBuffers) {
  25999. // Ubo replacement
  26000. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26001. return p1 + "{X}";
  26002. });
  26003. }
  26004. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26005. }
  26006. }
  26007. else {
  26008. if (!this._engine.supportsUniformBuffers) {
  26009. // Ubo replacement
  26010. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26011. return p1 + "{X}";
  26012. });
  26013. }
  26014. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26015. }
  26016. }
  26017. // Replace
  26018. returnValue = returnValue.replace(match[0], includeContent);
  26019. }
  26020. else {
  26021. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26022. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26023. Effect.IncludesShadersStore[includeFile] = fileContent;
  26024. _this._processIncludes(returnValue, callback);
  26025. });
  26026. return;
  26027. }
  26028. match = regex.exec(sourceCode);
  26029. }
  26030. callback(returnValue);
  26031. };
  26032. Effect.prototype._processPrecision = function (source) {
  26033. if (source.indexOf("precision highp float") === -1) {
  26034. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26035. source = "precision mediump float;\n" + source;
  26036. }
  26037. else {
  26038. source = "precision highp float;\n" + source;
  26039. }
  26040. }
  26041. else {
  26042. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26043. source = source.replace("precision highp float", "precision mediump float");
  26044. }
  26045. }
  26046. return source;
  26047. };
  26048. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26049. var _this = this;
  26050. this._isReady = false;
  26051. this._vertexSourceCodeOverride = vertexSourceCode;
  26052. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26053. this.onError = function (effect, error) {
  26054. if (onError) {
  26055. onError(error);
  26056. }
  26057. };
  26058. this.onCompiled = function () {
  26059. var scenes = _this.getEngine().scenes;
  26060. for (var i = 0; i < scenes.length; i++) {
  26061. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26062. }
  26063. if (onCompiled) {
  26064. onCompiled(_this._program);
  26065. }
  26066. };
  26067. this._fallbacks = null;
  26068. this._prepareEffect();
  26069. };
  26070. Effect.prototype._prepareEffect = function () {
  26071. var attributesNames = this._attributesNames;
  26072. var defines = this.defines;
  26073. var fallbacks = this._fallbacks;
  26074. this._valueCache = {};
  26075. var previousProgram = this._program;
  26076. try {
  26077. var engine = this._engine;
  26078. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26079. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26080. }
  26081. else {
  26082. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26083. }
  26084. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26085. if (engine.webGLVersion > 1) {
  26086. for (var name in this._uniformBuffersNames) {
  26087. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26088. }
  26089. }
  26090. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26091. this._attributes = engine.getAttributes(this._program, attributesNames);
  26092. var index;
  26093. for (index = 0; index < this._samplers.length; index++) {
  26094. var sampler = this.getUniform(this._samplers[index]);
  26095. if (sampler == null) {
  26096. this._samplers.splice(index, 1);
  26097. index--;
  26098. }
  26099. }
  26100. engine.bindSamplers(this);
  26101. this._compilationError = "";
  26102. this._isReady = true;
  26103. if (this.onCompiled) {
  26104. this.onCompiled(this);
  26105. }
  26106. this.onCompileObservable.notifyObservers(this);
  26107. this.onCompileObservable.clear();
  26108. // Unbind mesh reference in fallbacks
  26109. if (this._fallbacks) {
  26110. this._fallbacks.unBindMesh();
  26111. }
  26112. if (previousProgram) {
  26113. this.getEngine()._deleteProgram(previousProgram);
  26114. }
  26115. }
  26116. catch (e) {
  26117. this._compilationError = e.message;
  26118. // Let's go through fallbacks then
  26119. BABYLON.Tools.Error("Unable to compile effect:");
  26120. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26121. return " " + uniform;
  26122. }));
  26123. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26124. return " " + attribute;
  26125. }));
  26126. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26127. BABYLON.Tools.Error("Error: " + this._compilationError);
  26128. if (previousProgram) {
  26129. this._program = previousProgram;
  26130. this._isReady = true;
  26131. if (this.onError) {
  26132. this.onError(this, this._compilationError);
  26133. }
  26134. this.onErrorObservable.notifyObservers(this);
  26135. }
  26136. if (fallbacks && fallbacks.isMoreFallbacks) {
  26137. BABYLON.Tools.Error("Trying next fallback.");
  26138. this.defines = fallbacks.reduce(this.defines);
  26139. this._prepareEffect();
  26140. }
  26141. else {
  26142. if (this.onError) {
  26143. this.onError(this, this._compilationError);
  26144. }
  26145. this.onErrorObservable.notifyObservers(this);
  26146. this.onErrorObservable.clear();
  26147. // Unbind mesh reference in fallbacks
  26148. if (this._fallbacks) {
  26149. this._fallbacks.unBindMesh();
  26150. }
  26151. }
  26152. }
  26153. };
  26154. Object.defineProperty(Effect.prototype, "isSupported", {
  26155. get: function () {
  26156. return this._compilationError === "";
  26157. },
  26158. enumerable: true,
  26159. configurable: true
  26160. });
  26161. Effect.prototype._bindTexture = function (channel, texture) {
  26162. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26163. };
  26164. Effect.prototype.setTexture = function (channel, texture) {
  26165. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26166. };
  26167. Effect.prototype.setTextureArray = function (channel, textures) {
  26168. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26169. var initialPos = this._samplers.indexOf(channel);
  26170. for (var index = 1; index < textures.length; index++) {
  26171. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26172. }
  26173. }
  26174. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26175. };
  26176. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26177. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26178. };
  26179. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26180. var cache = this._valueCache[uniformName];
  26181. var flag = matrix.updateFlag;
  26182. if (cache !== undefined && cache === flag) {
  26183. return false;
  26184. }
  26185. this._valueCache[uniformName] = flag;
  26186. return true;
  26187. };
  26188. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26189. var cache = this._valueCache[uniformName];
  26190. if (!cache) {
  26191. cache = [x, y];
  26192. this._valueCache[uniformName] = cache;
  26193. return true;
  26194. }
  26195. var changed = false;
  26196. if (cache[0] !== x) {
  26197. cache[0] = x;
  26198. changed = true;
  26199. }
  26200. if (cache[1] !== y) {
  26201. cache[1] = y;
  26202. changed = true;
  26203. }
  26204. return changed;
  26205. };
  26206. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26207. var cache = this._valueCache[uniformName];
  26208. if (!cache) {
  26209. cache = [x, y, z];
  26210. this._valueCache[uniformName] = cache;
  26211. return true;
  26212. }
  26213. var changed = false;
  26214. if (cache[0] !== x) {
  26215. cache[0] = x;
  26216. changed = true;
  26217. }
  26218. if (cache[1] !== y) {
  26219. cache[1] = y;
  26220. changed = true;
  26221. }
  26222. if (cache[2] !== z) {
  26223. cache[2] = z;
  26224. changed = true;
  26225. }
  26226. return changed;
  26227. };
  26228. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26229. var cache = this._valueCache[uniformName];
  26230. if (!cache) {
  26231. cache = [x, y, z, w];
  26232. this._valueCache[uniformName] = cache;
  26233. return true;
  26234. }
  26235. var changed = false;
  26236. if (cache[0] !== x) {
  26237. cache[0] = x;
  26238. changed = true;
  26239. }
  26240. if (cache[1] !== y) {
  26241. cache[1] = y;
  26242. changed = true;
  26243. }
  26244. if (cache[2] !== z) {
  26245. cache[2] = z;
  26246. changed = true;
  26247. }
  26248. if (cache[3] !== w) {
  26249. cache[3] = w;
  26250. changed = true;
  26251. }
  26252. return changed;
  26253. };
  26254. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26255. var bufferName = this._uniformBuffersNames[name];
  26256. if (Effect._baseCache[bufferName] === buffer) {
  26257. return;
  26258. }
  26259. Effect._baseCache[bufferName] = buffer;
  26260. this._engine.bindUniformBufferBase(buffer, bufferName);
  26261. };
  26262. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26263. this._engine.bindUniformBlock(this._program, blockName, index);
  26264. };
  26265. Effect.prototype.setIntArray = function (uniformName, array) {
  26266. this._valueCache[uniformName] = null;
  26267. this._engine.setIntArray(this.getUniform(uniformName), array);
  26268. return this;
  26269. };
  26270. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26271. this._valueCache[uniformName] = null;
  26272. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26273. return this;
  26274. };
  26275. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26276. this._valueCache[uniformName] = null;
  26277. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26278. return this;
  26279. };
  26280. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26281. this._valueCache[uniformName] = null;
  26282. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26283. return this;
  26284. };
  26285. Effect.prototype.setFloatArray = function (uniformName, array) {
  26286. this._valueCache[uniformName] = null;
  26287. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26288. return this;
  26289. };
  26290. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26291. this._valueCache[uniformName] = null;
  26292. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26293. return this;
  26294. };
  26295. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26296. this._valueCache[uniformName] = null;
  26297. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26298. return this;
  26299. };
  26300. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26301. this._valueCache[uniformName] = null;
  26302. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26303. return this;
  26304. };
  26305. Effect.prototype.setArray = function (uniformName, array) {
  26306. this._valueCache[uniformName] = null;
  26307. this._engine.setArray(this.getUniform(uniformName), array);
  26308. return this;
  26309. };
  26310. Effect.prototype.setArray2 = function (uniformName, array) {
  26311. this._valueCache[uniformName] = null;
  26312. this._engine.setArray2(this.getUniform(uniformName), array);
  26313. return this;
  26314. };
  26315. Effect.prototype.setArray3 = function (uniformName, array) {
  26316. this._valueCache[uniformName] = null;
  26317. this._engine.setArray3(this.getUniform(uniformName), array);
  26318. return this;
  26319. };
  26320. Effect.prototype.setArray4 = function (uniformName, array) {
  26321. this._valueCache[uniformName] = null;
  26322. this._engine.setArray4(this.getUniform(uniformName), array);
  26323. return this;
  26324. };
  26325. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26326. if (!matrices) {
  26327. return this;
  26328. }
  26329. this._valueCache[uniformName] = null;
  26330. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26331. return this;
  26332. };
  26333. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26334. if (this._cacheMatrix(uniformName, matrix)) {
  26335. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26336. }
  26337. return this;
  26338. };
  26339. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26340. this._valueCache[uniformName] = null;
  26341. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26342. return this;
  26343. };
  26344. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26345. this._valueCache[uniformName] = null;
  26346. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26347. return this;
  26348. };
  26349. Effect.prototype.setFloat = function (uniformName, value) {
  26350. var cache = this._valueCache[uniformName];
  26351. if (cache !== undefined && cache === value)
  26352. return this;
  26353. this._valueCache[uniformName] = value;
  26354. this._engine.setFloat(this.getUniform(uniformName), value);
  26355. return this;
  26356. };
  26357. Effect.prototype.setBool = function (uniformName, bool) {
  26358. var cache = this._valueCache[uniformName];
  26359. if (cache !== undefined && cache === bool)
  26360. return this;
  26361. this._valueCache[uniformName] = bool;
  26362. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26363. return this;
  26364. };
  26365. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26366. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26367. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26368. }
  26369. return this;
  26370. };
  26371. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26372. if (this._cacheFloat2(uniformName, x, y)) {
  26373. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26374. }
  26375. return this;
  26376. };
  26377. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26378. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26379. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26380. }
  26381. return this;
  26382. };
  26383. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26384. if (this._cacheFloat3(uniformName, x, y, z)) {
  26385. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26386. }
  26387. return this;
  26388. };
  26389. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26390. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26391. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26392. }
  26393. return this;
  26394. };
  26395. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26396. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26397. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26398. }
  26399. return this;
  26400. };
  26401. Effect.prototype.setColor3 = function (uniformName, color3) {
  26402. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26403. this._engine.setColor3(this.getUniform(uniformName), color3);
  26404. }
  26405. return this;
  26406. };
  26407. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26408. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26409. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26410. }
  26411. return this;
  26412. };
  26413. Effect.ResetCache = function () {
  26414. Effect._baseCache = {};
  26415. };
  26416. Effect._uniqueIdSeed = 0;
  26417. Effect._baseCache = {};
  26418. // Statics
  26419. Effect.ShadersStore = {};
  26420. Effect.IncludesShadersStore = {};
  26421. return Effect;
  26422. }());
  26423. BABYLON.Effect = Effect;
  26424. })(BABYLON || (BABYLON = {}));
  26425. //# sourceMappingURL=babylon.effect.js.map
  26426. var BABYLON;
  26427. (function (BABYLON) {
  26428. var MaterialHelper = /** @class */ (function () {
  26429. function MaterialHelper() {
  26430. }
  26431. MaterialHelper.BindEyePosition = function (effect, scene) {
  26432. if (scene._forcedViewPosition) {
  26433. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26434. return;
  26435. }
  26436. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26437. };
  26438. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26439. defines._needUVs = true;
  26440. defines[key] = true;
  26441. if (texture.getTextureMatrix().isIdentity(true)) {
  26442. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26443. if (texture.coordinatesIndex === 0) {
  26444. defines["MAINUV1"] = true;
  26445. }
  26446. else {
  26447. defines["MAINUV2"] = true;
  26448. }
  26449. }
  26450. else {
  26451. defines[key + "DIRECTUV"] = 0;
  26452. }
  26453. };
  26454. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26455. var matrix = texture.getTextureMatrix();
  26456. if (!matrix.isIdentity(true)) {
  26457. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26458. }
  26459. };
  26460. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26461. if (defines._areMiscDirty) {
  26462. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26463. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26464. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26465. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26466. }
  26467. };
  26468. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26469. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26470. var changed = false;
  26471. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26472. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26473. changed = true;
  26474. }
  26475. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26476. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26477. changed = true;
  26478. }
  26479. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26480. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26481. changed = true;
  26482. }
  26483. if (defines["INSTANCES"] !== useInstances) {
  26484. defines["INSTANCES"] = useInstances;
  26485. changed = true;
  26486. }
  26487. if (changed) {
  26488. defines.markAsUnprocessed();
  26489. }
  26490. };
  26491. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26492. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26493. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26494. return false;
  26495. }
  26496. defines._normals = defines._needNormals;
  26497. defines._uvs = defines._needUVs;
  26498. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26499. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26500. defines["TANGENT"] = true;
  26501. }
  26502. if (defines._needUVs) {
  26503. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26504. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26505. }
  26506. else {
  26507. defines["UV1"] = false;
  26508. defines["UV2"] = false;
  26509. }
  26510. if (useVertexColor) {
  26511. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26512. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26513. }
  26514. if (useBones) {
  26515. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26516. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26517. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26518. }
  26519. else {
  26520. defines["NUM_BONE_INFLUENCERS"] = 0;
  26521. defines["BonesPerMesh"] = 0;
  26522. }
  26523. }
  26524. if (useMorphTargets) {
  26525. var manager = mesh.morphTargetManager;
  26526. if (manager) {
  26527. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26528. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26529. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26530. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26531. }
  26532. else {
  26533. defines["MORPHTARGETS_TANGENT"] = false;
  26534. defines["MORPHTARGETS_NORMAL"] = false;
  26535. defines["MORPHTARGETS"] = false;
  26536. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26537. }
  26538. }
  26539. return true;
  26540. };
  26541. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26542. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26543. if (disableLighting === void 0) { disableLighting = false; }
  26544. if (!defines._areLightsDirty) {
  26545. return defines._needNormals;
  26546. }
  26547. var lightIndex = 0;
  26548. var needNormals = false;
  26549. var needRebuild = false;
  26550. var lightmapMode = false;
  26551. var shadowEnabled = false;
  26552. var specularEnabled = false;
  26553. if (scene.lightsEnabled && !disableLighting) {
  26554. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26555. var light = _a[_i];
  26556. needNormals = true;
  26557. if (defines["LIGHT" + lightIndex] === undefined) {
  26558. needRebuild = true;
  26559. }
  26560. defines["LIGHT" + lightIndex] = true;
  26561. defines["SPOTLIGHT" + lightIndex] = false;
  26562. defines["HEMILIGHT" + lightIndex] = false;
  26563. defines["POINTLIGHT" + lightIndex] = false;
  26564. defines["DIRLIGHT" + lightIndex] = false;
  26565. var type;
  26566. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26567. type = "SPOTLIGHT" + lightIndex;
  26568. }
  26569. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26570. type = "HEMILIGHT" + lightIndex;
  26571. }
  26572. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26573. type = "POINTLIGHT" + lightIndex;
  26574. }
  26575. else {
  26576. type = "DIRLIGHT" + lightIndex;
  26577. }
  26578. defines[type] = true;
  26579. // Specular
  26580. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26581. specularEnabled = true;
  26582. }
  26583. // Shadows
  26584. defines["SHADOW" + lightIndex] = false;
  26585. defines["SHADOWPCF" + lightIndex] = false;
  26586. defines["SHADOWESM" + lightIndex] = false;
  26587. defines["SHADOWCUBE" + lightIndex] = false;
  26588. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26589. var shadowGenerator = light.getShadowGenerator();
  26590. if (shadowGenerator) {
  26591. shadowEnabled = true;
  26592. shadowGenerator.prepareDefines(defines, lightIndex);
  26593. }
  26594. }
  26595. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26596. lightmapMode = true;
  26597. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26598. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26599. }
  26600. else {
  26601. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26602. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26603. }
  26604. lightIndex++;
  26605. if (lightIndex === maxSimultaneousLights)
  26606. break;
  26607. }
  26608. }
  26609. defines["SPECULARTERM"] = specularEnabled;
  26610. defines["SHADOWS"] = shadowEnabled;
  26611. // Resetting all other lights if any
  26612. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26613. if (defines["LIGHT" + index] !== undefined) {
  26614. defines["LIGHT" + index] = false;
  26615. defines["HEMILIGHT" + lightIndex] = false;
  26616. defines["POINTLIGHT" + lightIndex] = false;
  26617. defines["DIRLIGHT" + lightIndex] = false;
  26618. defines["SPOTLIGHT" + lightIndex] = false;
  26619. defines["SHADOW" + lightIndex] = false;
  26620. }
  26621. }
  26622. var caps = scene.getEngine().getCaps();
  26623. if (defines["SHADOWFLOAT"] === undefined) {
  26624. needRebuild = true;
  26625. }
  26626. defines["SHADOWFLOAT"] = shadowEnabled &&
  26627. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26628. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26629. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26630. if (needRebuild) {
  26631. defines.rebuild();
  26632. }
  26633. return needNormals;
  26634. };
  26635. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26636. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26637. var uniformsList;
  26638. var uniformBuffersList = null;
  26639. if (uniformsListOrOptions.uniformsNames) {
  26640. var options = uniformsListOrOptions;
  26641. uniformsList = options.uniformsNames;
  26642. uniformBuffersList = options.uniformBuffersNames;
  26643. samplersList = options.samplers;
  26644. defines = options.defines;
  26645. maxSimultaneousLights = options.maxSimultaneousLights;
  26646. }
  26647. else {
  26648. uniformsList = uniformsListOrOptions;
  26649. if (!samplersList) {
  26650. samplersList = [];
  26651. }
  26652. }
  26653. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26654. if (!defines["LIGHT" + lightIndex]) {
  26655. break;
  26656. }
  26657. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26658. if (uniformBuffersList) {
  26659. uniformBuffersList.push("Light" + lightIndex);
  26660. }
  26661. samplersList.push("shadowSampler" + lightIndex);
  26662. }
  26663. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26664. uniformsList.push("morphTargetInfluences");
  26665. }
  26666. };
  26667. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  26668. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26669. if (rank === void 0) { rank = 0; }
  26670. var lightFallbackRank = 0;
  26671. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26672. if (!defines["LIGHT" + lightIndex]) {
  26673. break;
  26674. }
  26675. if (lightIndex > 0) {
  26676. lightFallbackRank = rank + lightIndex;
  26677. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  26678. }
  26679. if (!defines["SHADOWS"]) {
  26680. if (defines["SHADOW" + lightIndex]) {
  26681. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  26682. }
  26683. if (defines["SHADOWPCF" + lightIndex]) {
  26684. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  26685. }
  26686. if (defines["SHADOWESM" + lightIndex]) {
  26687. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  26688. }
  26689. }
  26690. }
  26691. return lightFallbackRank++;
  26692. };
  26693. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26694. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26695. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26696. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26697. var manager = mesh.morphTargetManager;
  26698. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26699. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26700. for (var index = 0; index < influencers; index++) {
  26701. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26702. if (normal) {
  26703. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26704. }
  26705. if (tangent) {
  26706. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26707. }
  26708. if (attribs.length > maxAttributesCount) {
  26709. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26710. }
  26711. }
  26712. }
  26713. };
  26714. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26715. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26716. fallbacks.addCPUSkinningFallback(0, mesh);
  26717. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26718. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26719. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26720. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26721. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26722. }
  26723. }
  26724. };
  26725. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26726. if (defines["INSTANCES"]) {
  26727. attribs.push("world0");
  26728. attribs.push("world1");
  26729. attribs.push("world2");
  26730. attribs.push("world3");
  26731. }
  26732. };
  26733. // Bindings
  26734. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26735. if (light.shadowEnabled && mesh.receiveShadows) {
  26736. var shadowGenerator = light.getShadowGenerator();
  26737. if (shadowGenerator) {
  26738. shadowGenerator.bindShadowLight(lightIndex, effect);
  26739. }
  26740. }
  26741. };
  26742. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26743. light.transferToEffect(effect, lightIndex + "");
  26744. };
  26745. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26746. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26747. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26748. var lightIndex = 0;
  26749. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26750. var light = _a[_i];
  26751. var scaledIntensity = light.getScaledIntensity();
  26752. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26753. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26754. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26755. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26756. if (defines["SPECULARTERM"]) {
  26757. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26758. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26759. }
  26760. // Shadows
  26761. if (scene.shadowsEnabled) {
  26762. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26763. }
  26764. light._uniformBuffer.update();
  26765. lightIndex++;
  26766. if (lightIndex === maxSimultaneousLights)
  26767. break;
  26768. }
  26769. };
  26770. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26771. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26772. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26773. effect.setColor3("vFogColor", scene.fogColor);
  26774. }
  26775. };
  26776. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26777. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26778. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26779. if (matrices && effect) {
  26780. effect.setMatrices("mBones", matrices);
  26781. }
  26782. }
  26783. };
  26784. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26785. var manager = abstractMesh.morphTargetManager;
  26786. if (!abstractMesh || !manager) {
  26787. return;
  26788. }
  26789. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26790. };
  26791. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26792. if (defines["LOGARITHMICDEPTH"]) {
  26793. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26794. }
  26795. };
  26796. MaterialHelper.BindClipPlane = function (effect, scene) {
  26797. if (scene.clipPlane) {
  26798. var clipPlane = scene.clipPlane;
  26799. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26800. }
  26801. };
  26802. return MaterialHelper;
  26803. }());
  26804. BABYLON.MaterialHelper = MaterialHelper;
  26805. })(BABYLON || (BABYLON = {}));
  26806. //# sourceMappingURL=babylon.materialHelper.js.map
  26807. var BABYLON;
  26808. (function (BABYLON) {
  26809. var MaterialDefines = /** @class */ (function () {
  26810. function MaterialDefines() {
  26811. this._isDirty = true;
  26812. this._areLightsDirty = true;
  26813. this._areAttributesDirty = true;
  26814. this._areTexturesDirty = true;
  26815. this._areFresnelDirty = true;
  26816. this._areMiscDirty = true;
  26817. this._areImageProcessingDirty = true;
  26818. this._normals = false;
  26819. this._uvs = false;
  26820. this._needNormals = false;
  26821. this._needUVs = false;
  26822. }
  26823. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26824. get: function () {
  26825. return this._isDirty;
  26826. },
  26827. enumerable: true,
  26828. configurable: true
  26829. });
  26830. MaterialDefines.prototype.markAsProcessed = function () {
  26831. this._isDirty = false;
  26832. this._areAttributesDirty = false;
  26833. this._areTexturesDirty = false;
  26834. this._areFresnelDirty = false;
  26835. this._areLightsDirty = false;
  26836. this._areMiscDirty = false;
  26837. this._areImageProcessingDirty = false;
  26838. };
  26839. MaterialDefines.prototype.markAsUnprocessed = function () {
  26840. this._isDirty = true;
  26841. };
  26842. MaterialDefines.prototype.markAllAsDirty = function () {
  26843. this._areTexturesDirty = true;
  26844. this._areAttributesDirty = true;
  26845. this._areLightsDirty = true;
  26846. this._areFresnelDirty = true;
  26847. this._areMiscDirty = true;
  26848. this._areImageProcessingDirty = true;
  26849. this._isDirty = true;
  26850. };
  26851. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26852. this._areImageProcessingDirty = true;
  26853. this._isDirty = true;
  26854. };
  26855. MaterialDefines.prototype.markAsLightDirty = function () {
  26856. this._areLightsDirty = true;
  26857. this._isDirty = true;
  26858. };
  26859. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26860. this._areAttributesDirty = true;
  26861. this._isDirty = true;
  26862. };
  26863. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26864. this._areTexturesDirty = true;
  26865. this._isDirty = true;
  26866. };
  26867. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26868. this._areFresnelDirty = true;
  26869. this._isDirty = true;
  26870. };
  26871. MaterialDefines.prototype.markAsMiscDirty = function () {
  26872. this._areMiscDirty = true;
  26873. this._isDirty = true;
  26874. };
  26875. MaterialDefines.prototype.rebuild = function () {
  26876. if (this._keys) {
  26877. delete this._keys;
  26878. }
  26879. this._keys = [];
  26880. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26881. var key = _a[_i];
  26882. if (key[0] === "_") {
  26883. continue;
  26884. }
  26885. this._keys.push(key);
  26886. }
  26887. };
  26888. MaterialDefines.prototype.isEqual = function (other) {
  26889. if (this._keys.length !== other._keys.length) {
  26890. return false;
  26891. }
  26892. for (var index = 0; index < this._keys.length; index++) {
  26893. var prop = this._keys[index];
  26894. if (this[prop] !== other[prop]) {
  26895. return false;
  26896. }
  26897. }
  26898. return true;
  26899. };
  26900. MaterialDefines.prototype.cloneTo = function (other) {
  26901. if (this._keys.length !== other._keys.length) {
  26902. other._keys = this._keys.slice(0);
  26903. }
  26904. for (var index = 0; index < this._keys.length; index++) {
  26905. var prop = this._keys[index];
  26906. other[prop] = this[prop];
  26907. }
  26908. };
  26909. MaterialDefines.prototype.reset = function () {
  26910. for (var index = 0; index < this._keys.length; index++) {
  26911. var prop = this._keys[index];
  26912. if (typeof (this[prop]) === "number") {
  26913. this[prop] = 0;
  26914. }
  26915. else {
  26916. this[prop] = false;
  26917. }
  26918. }
  26919. };
  26920. MaterialDefines.prototype.toString = function () {
  26921. var result = "";
  26922. for (var index = 0; index < this._keys.length; index++) {
  26923. var prop = this._keys[index];
  26924. var value = this[prop];
  26925. if (typeof (value) === "number") {
  26926. result += "#define " + prop + " " + this[prop] + "\n";
  26927. }
  26928. else if (value) {
  26929. result += "#define " + prop + "\n";
  26930. }
  26931. }
  26932. return result;
  26933. };
  26934. return MaterialDefines;
  26935. }());
  26936. BABYLON.MaterialDefines = MaterialDefines;
  26937. var Material = /** @class */ (function () {
  26938. function Material(name, scene, doNotAdd) {
  26939. this.checkReadyOnEveryCall = false;
  26940. this.checkReadyOnlyOnce = false;
  26941. this.state = "";
  26942. this.alpha = 1.0;
  26943. this._backFaceCulling = true;
  26944. this.doNotSerialize = false;
  26945. this.storeEffectOnSubMeshes = false;
  26946. /**
  26947. * An event triggered when the material is disposed.
  26948. * @type {BABYLON.Observable}
  26949. */
  26950. this.onDisposeObservable = new BABYLON.Observable();
  26951. /**
  26952. * An event triggered when the material is bound.
  26953. * @type {BABYLON.Observable}
  26954. */
  26955. this.onBindObservable = new BABYLON.Observable();
  26956. /**
  26957. * An event triggered when the material is unbound.
  26958. * @type {BABYLON.Observable}
  26959. */
  26960. this.onUnBindObservable = new BABYLON.Observable();
  26961. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26962. this._needDepthPrePass = false;
  26963. this.disableDepthWrite = false;
  26964. this.forceDepthWrite = false;
  26965. this.separateCullingPass = false;
  26966. this._fogEnabled = true;
  26967. this.pointSize = 1.0;
  26968. this.zOffset = 0;
  26969. this._wasPreviouslyReady = false;
  26970. this._fillMode = Material.TriangleFillMode;
  26971. this.name = name;
  26972. this.id = name || BABYLON.Tools.RandomId();
  26973. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26974. if (this._scene.useRightHandedSystem) {
  26975. this.sideOrientation = Material.ClockWiseSideOrientation;
  26976. }
  26977. else {
  26978. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26979. }
  26980. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26981. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26982. if (!doNotAdd) {
  26983. this._scene.materials.push(this);
  26984. }
  26985. }
  26986. Object.defineProperty(Material, "TriangleFillMode", {
  26987. get: function () {
  26988. return Material._TriangleFillMode;
  26989. },
  26990. enumerable: true,
  26991. configurable: true
  26992. });
  26993. Object.defineProperty(Material, "WireFrameFillMode", {
  26994. get: function () {
  26995. return Material._WireFrameFillMode;
  26996. },
  26997. enumerable: true,
  26998. configurable: true
  26999. });
  27000. Object.defineProperty(Material, "PointFillMode", {
  27001. get: function () {
  27002. return Material._PointFillMode;
  27003. },
  27004. enumerable: true,
  27005. configurable: true
  27006. });
  27007. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27008. get: function () {
  27009. return Material._ClockWiseSideOrientation;
  27010. },
  27011. enumerable: true,
  27012. configurable: true
  27013. });
  27014. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27015. get: function () {
  27016. return Material._CounterClockWiseSideOrientation;
  27017. },
  27018. enumerable: true,
  27019. configurable: true
  27020. });
  27021. Object.defineProperty(Material, "TextureDirtyFlag", {
  27022. get: function () {
  27023. return Material._TextureDirtyFlag;
  27024. },
  27025. enumerable: true,
  27026. configurable: true
  27027. });
  27028. Object.defineProperty(Material, "LightDirtyFlag", {
  27029. get: function () {
  27030. return Material._LightDirtyFlag;
  27031. },
  27032. enumerable: true,
  27033. configurable: true
  27034. });
  27035. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27036. get: function () {
  27037. return Material._FresnelDirtyFlag;
  27038. },
  27039. enumerable: true,
  27040. configurable: true
  27041. });
  27042. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27043. get: function () {
  27044. return Material._AttributesDirtyFlag;
  27045. },
  27046. enumerable: true,
  27047. configurable: true
  27048. });
  27049. Object.defineProperty(Material, "MiscDirtyFlag", {
  27050. get: function () {
  27051. return Material._MiscDirtyFlag;
  27052. },
  27053. enumerable: true,
  27054. configurable: true
  27055. });
  27056. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27057. get: function () {
  27058. return this._backFaceCulling;
  27059. },
  27060. set: function (value) {
  27061. if (this._backFaceCulling === value) {
  27062. return;
  27063. }
  27064. this._backFaceCulling = value;
  27065. this.markAsDirty(Material.TextureDirtyFlag);
  27066. },
  27067. enumerable: true,
  27068. configurable: true
  27069. });
  27070. Object.defineProperty(Material.prototype, "onDispose", {
  27071. set: function (callback) {
  27072. if (this._onDisposeObserver) {
  27073. this.onDisposeObservable.remove(this._onDisposeObserver);
  27074. }
  27075. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. Object.defineProperty(Material.prototype, "onBind", {
  27081. set: function (callback) {
  27082. if (this._onBindObserver) {
  27083. this.onBindObservable.remove(this._onBindObserver);
  27084. }
  27085. this._onBindObserver = this.onBindObservable.add(callback);
  27086. },
  27087. enumerable: true,
  27088. configurable: true
  27089. });
  27090. Object.defineProperty(Material.prototype, "alphaMode", {
  27091. get: function () {
  27092. return this._alphaMode;
  27093. },
  27094. set: function (value) {
  27095. if (this._alphaMode === value) {
  27096. return;
  27097. }
  27098. this._alphaMode = value;
  27099. this.markAsDirty(Material.TextureDirtyFlag);
  27100. },
  27101. enumerable: true,
  27102. configurable: true
  27103. });
  27104. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27105. get: function () {
  27106. return this._needDepthPrePass;
  27107. },
  27108. set: function (value) {
  27109. if (this._needDepthPrePass === value) {
  27110. return;
  27111. }
  27112. this._needDepthPrePass = value;
  27113. if (this._needDepthPrePass) {
  27114. this.checkReadyOnEveryCall = true;
  27115. }
  27116. },
  27117. enumerable: true,
  27118. configurable: true
  27119. });
  27120. Object.defineProperty(Material.prototype, "fogEnabled", {
  27121. get: function () {
  27122. return this._fogEnabled;
  27123. },
  27124. set: function (value) {
  27125. if (this._fogEnabled === value) {
  27126. return;
  27127. }
  27128. this._fogEnabled = value;
  27129. this.markAsDirty(Material.MiscDirtyFlag);
  27130. },
  27131. enumerable: true,
  27132. configurable: true
  27133. });
  27134. Object.defineProperty(Material.prototype, "wireframe", {
  27135. get: function () {
  27136. return this._fillMode === Material.WireFrameFillMode;
  27137. },
  27138. set: function (value) {
  27139. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27140. },
  27141. enumerable: true,
  27142. configurable: true
  27143. });
  27144. Object.defineProperty(Material.prototype, "pointsCloud", {
  27145. get: function () {
  27146. return this._fillMode === Material.PointFillMode;
  27147. },
  27148. set: function (value) {
  27149. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27150. },
  27151. enumerable: true,
  27152. configurable: true
  27153. });
  27154. Object.defineProperty(Material.prototype, "fillMode", {
  27155. get: function () {
  27156. return this._fillMode;
  27157. },
  27158. set: function (value) {
  27159. if (this._fillMode === value) {
  27160. return;
  27161. }
  27162. this._fillMode = value;
  27163. this.markAsDirty(Material.MiscDirtyFlag);
  27164. },
  27165. enumerable: true,
  27166. configurable: true
  27167. });
  27168. /**
  27169. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27170. * subclasses should override adding information pertainent to themselves
  27171. */
  27172. Material.prototype.toString = function (fullDetails) {
  27173. var ret = "Name: " + this.name;
  27174. if (fullDetails) {
  27175. }
  27176. return ret;
  27177. };
  27178. /**
  27179. * Child classes can use it to update shaders
  27180. */
  27181. Material.prototype.getClassName = function () {
  27182. return "Material";
  27183. };
  27184. Object.defineProperty(Material.prototype, "isFrozen", {
  27185. get: function () {
  27186. return this.checkReadyOnlyOnce;
  27187. },
  27188. enumerable: true,
  27189. configurable: true
  27190. });
  27191. Material.prototype.freeze = function () {
  27192. this.checkReadyOnlyOnce = true;
  27193. };
  27194. Material.prototype.unfreeze = function () {
  27195. this.checkReadyOnlyOnce = false;
  27196. };
  27197. Material.prototype.isReady = function (mesh, useInstances) {
  27198. return true;
  27199. };
  27200. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27201. return false;
  27202. };
  27203. Material.prototype.getEffect = function () {
  27204. return this._effect;
  27205. };
  27206. Material.prototype.getScene = function () {
  27207. return this._scene;
  27208. };
  27209. Material.prototype.needAlphaBlending = function () {
  27210. return (this.alpha < 1.0);
  27211. };
  27212. Material.prototype.needAlphaTesting = function () {
  27213. return false;
  27214. };
  27215. Material.prototype.getAlphaTestTexture = function () {
  27216. return null;
  27217. };
  27218. Material.prototype.markDirty = function () {
  27219. this._wasPreviouslyReady = false;
  27220. };
  27221. Material.prototype._preBind = function (effect, overrideOrientation) {
  27222. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27223. var engine = this._scene.getEngine();
  27224. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27225. var reverse = orientation === Material.ClockWiseSideOrientation;
  27226. engine.enableEffect(effect ? effect : this._effect);
  27227. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27228. return reverse;
  27229. };
  27230. Material.prototype.bind = function (world, mesh) {
  27231. };
  27232. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27233. };
  27234. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27235. };
  27236. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27237. sceneUbo.bindToEffect(effect, "Scene");
  27238. };
  27239. Material.prototype.bindView = function (effect) {
  27240. if (!this._useUBO) {
  27241. effect.setMatrix("view", this.getScene().getViewMatrix());
  27242. }
  27243. else {
  27244. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27245. }
  27246. };
  27247. Material.prototype.bindViewProjection = function (effect) {
  27248. if (!this._useUBO) {
  27249. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27250. }
  27251. else {
  27252. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27253. }
  27254. };
  27255. Material.prototype._afterBind = function (mesh) {
  27256. this._scene._cachedMaterial = this;
  27257. if (mesh) {
  27258. this._scene._cachedVisibility = mesh.visibility;
  27259. }
  27260. else {
  27261. this._scene._cachedVisibility = 1;
  27262. }
  27263. if (mesh) {
  27264. this.onBindObservable.notifyObservers(mesh);
  27265. }
  27266. if (this.disableDepthWrite) {
  27267. var engine = this._scene.getEngine();
  27268. this._cachedDepthWriteState = engine.getDepthWrite();
  27269. engine.setDepthWrite(false);
  27270. }
  27271. };
  27272. Material.prototype.unbind = function () {
  27273. this.onUnBindObservable.notifyObservers(this);
  27274. if (this.disableDepthWrite) {
  27275. var engine = this._scene.getEngine();
  27276. engine.setDepthWrite(this._cachedDepthWriteState);
  27277. }
  27278. };
  27279. Material.prototype.getActiveTextures = function () {
  27280. return [];
  27281. };
  27282. Material.prototype.hasTexture = function (texture) {
  27283. return false;
  27284. };
  27285. Material.prototype.clone = function (name) {
  27286. return null;
  27287. };
  27288. Material.prototype.getBindedMeshes = function () {
  27289. var result = new Array();
  27290. for (var index = 0; index < this._scene.meshes.length; index++) {
  27291. var mesh = this._scene.meshes[index];
  27292. if (mesh.material === this) {
  27293. result.push(mesh);
  27294. }
  27295. }
  27296. return result;
  27297. };
  27298. /**
  27299. * Force shader compilation including textures ready check
  27300. */
  27301. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27302. var _this = this;
  27303. var subMesh = new BABYLON.BaseSubMesh();
  27304. var scene = this.getScene();
  27305. var engine = scene.getEngine();
  27306. var checkReady = function () {
  27307. if (!_this._scene || !_this._scene.getEngine()) {
  27308. return;
  27309. }
  27310. if (subMesh._materialDefines) {
  27311. subMesh._materialDefines._renderId = -1;
  27312. }
  27313. var alphaTestState = engine.getAlphaTesting();
  27314. var clipPlaneState = scene.clipPlane;
  27315. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27316. if (options && options.clipPlane) {
  27317. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27318. }
  27319. if (_this.storeEffectOnSubMeshes) {
  27320. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27321. if (onCompiled) {
  27322. onCompiled(_this);
  27323. }
  27324. }
  27325. else {
  27326. setTimeout(checkReady, 16);
  27327. }
  27328. }
  27329. else {
  27330. if (_this.isReady(mesh)) {
  27331. if (onCompiled) {
  27332. onCompiled(_this);
  27333. }
  27334. }
  27335. else {
  27336. setTimeout(checkReady, 16);
  27337. }
  27338. }
  27339. engine.setAlphaTesting(alphaTestState);
  27340. if (options && options.clipPlane) {
  27341. scene.clipPlane = clipPlaneState;
  27342. }
  27343. };
  27344. checkReady();
  27345. };
  27346. Material.prototype.markAsDirty = function (flag) {
  27347. if (flag & Material.TextureDirtyFlag) {
  27348. this._markAllSubMeshesAsTexturesDirty();
  27349. }
  27350. if (flag & Material.LightDirtyFlag) {
  27351. this._markAllSubMeshesAsLightsDirty();
  27352. }
  27353. if (flag & Material.FresnelDirtyFlag) {
  27354. this._markAllSubMeshesAsFresnelDirty();
  27355. }
  27356. if (flag & Material.AttributesDirtyFlag) {
  27357. this._markAllSubMeshesAsAttributesDirty();
  27358. }
  27359. if (flag & Material.MiscDirtyFlag) {
  27360. this._markAllSubMeshesAsMiscDirty();
  27361. }
  27362. this.getScene().resetCachedMaterial();
  27363. };
  27364. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27365. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27366. var mesh = _a[_i];
  27367. if (!mesh.subMeshes) {
  27368. continue;
  27369. }
  27370. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27371. var subMesh = _c[_b];
  27372. if (subMesh.getMaterial() !== this) {
  27373. continue;
  27374. }
  27375. if (!subMesh._materialDefines) {
  27376. continue;
  27377. }
  27378. func(subMesh._materialDefines);
  27379. }
  27380. }
  27381. };
  27382. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27383. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27384. };
  27385. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27386. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27387. };
  27388. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27389. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27390. };
  27391. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27392. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27393. };
  27394. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27395. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27396. };
  27397. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27398. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27399. };
  27400. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27401. // Animations
  27402. this.getScene().stopAnimation(this);
  27403. // Remove from scene
  27404. var index = this._scene.materials.indexOf(this);
  27405. if (index >= 0) {
  27406. this._scene.materials.splice(index, 1);
  27407. }
  27408. // Remove from meshes
  27409. for (index = 0; index < this._scene.meshes.length; index++) {
  27410. var mesh = this._scene.meshes[index];
  27411. if (mesh.material === this) {
  27412. mesh.material = null;
  27413. if (mesh.geometry) {
  27414. var geometry = (mesh.geometry);
  27415. if (this.storeEffectOnSubMeshes) {
  27416. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27417. var subMesh = _a[_i];
  27418. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27419. if (forceDisposeEffect && subMesh._materialEffect) {
  27420. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27421. }
  27422. }
  27423. }
  27424. else {
  27425. geometry._releaseVertexArrayObject(this._effect);
  27426. }
  27427. }
  27428. }
  27429. }
  27430. this._uniformBuffer.dispose();
  27431. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27432. if (forceDisposeEffect && this._effect) {
  27433. if (!this.storeEffectOnSubMeshes) {
  27434. this._scene.getEngine()._releaseEffect(this._effect);
  27435. }
  27436. this._effect = null;
  27437. }
  27438. // Callback
  27439. this.onDisposeObservable.notifyObservers(this);
  27440. this.onDisposeObservable.clear();
  27441. this.onBindObservable.clear();
  27442. this.onUnBindObservable.clear();
  27443. };
  27444. Material.prototype.serialize = function () {
  27445. return BABYLON.SerializationHelper.Serialize(this);
  27446. };
  27447. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27448. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27449. multiMaterial.id = parsedMultiMaterial.id;
  27450. if (BABYLON.Tags) {
  27451. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27452. }
  27453. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27454. var subMatId = parsedMultiMaterial.materials[matIndex];
  27455. if (subMatId) {
  27456. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27457. }
  27458. else {
  27459. multiMaterial.subMaterials.push(null);
  27460. }
  27461. }
  27462. return multiMaterial;
  27463. };
  27464. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27465. if (!parsedMaterial.customType) {
  27466. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27467. }
  27468. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27469. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27470. if (!BABYLON.LegacyPBRMaterial) {
  27471. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27472. return;
  27473. }
  27474. }
  27475. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27476. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27477. ;
  27478. };
  27479. Material._TriangleFillMode = 0;
  27480. Material._WireFrameFillMode = 1;
  27481. Material._PointFillMode = 2;
  27482. Material._ClockWiseSideOrientation = 0;
  27483. Material._CounterClockWiseSideOrientation = 1;
  27484. Material._TextureDirtyFlag = 1;
  27485. Material._LightDirtyFlag = 2;
  27486. Material._FresnelDirtyFlag = 4;
  27487. Material._AttributesDirtyFlag = 8;
  27488. Material._MiscDirtyFlag = 16;
  27489. __decorate([
  27490. BABYLON.serialize()
  27491. ], Material.prototype, "id", void 0);
  27492. __decorate([
  27493. BABYLON.serialize()
  27494. ], Material.prototype, "name", void 0);
  27495. __decorate([
  27496. BABYLON.serialize()
  27497. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27498. __decorate([
  27499. BABYLON.serialize()
  27500. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27501. __decorate([
  27502. BABYLON.serialize()
  27503. ], Material.prototype, "state", void 0);
  27504. __decorate([
  27505. BABYLON.serialize()
  27506. ], Material.prototype, "alpha", void 0);
  27507. __decorate([
  27508. BABYLON.serialize("backFaceCulling")
  27509. ], Material.prototype, "_backFaceCulling", void 0);
  27510. __decorate([
  27511. BABYLON.serialize()
  27512. ], Material.prototype, "sideOrientation", void 0);
  27513. __decorate([
  27514. BABYLON.serialize("alphaMode")
  27515. ], Material.prototype, "_alphaMode", void 0);
  27516. __decorate([
  27517. BABYLON.serialize()
  27518. ], Material.prototype, "_needDepthPrePass", void 0);
  27519. __decorate([
  27520. BABYLON.serialize()
  27521. ], Material.prototype, "disableDepthWrite", void 0);
  27522. __decorate([
  27523. BABYLON.serialize()
  27524. ], Material.prototype, "forceDepthWrite", void 0);
  27525. __decorate([
  27526. BABYLON.serialize()
  27527. ], Material.prototype, "separateCullingPass", void 0);
  27528. __decorate([
  27529. BABYLON.serialize("fogEnabled")
  27530. ], Material.prototype, "_fogEnabled", void 0);
  27531. __decorate([
  27532. BABYLON.serialize()
  27533. ], Material.prototype, "pointSize", void 0);
  27534. __decorate([
  27535. BABYLON.serialize()
  27536. ], Material.prototype, "zOffset", void 0);
  27537. __decorate([
  27538. BABYLON.serialize()
  27539. ], Material.prototype, "wireframe", null);
  27540. __decorate([
  27541. BABYLON.serialize()
  27542. ], Material.prototype, "pointsCloud", null);
  27543. __decorate([
  27544. BABYLON.serialize()
  27545. ], Material.prototype, "fillMode", null);
  27546. return Material;
  27547. }());
  27548. BABYLON.Material = Material;
  27549. })(BABYLON || (BABYLON = {}));
  27550. //# sourceMappingURL=babylon.material.js.map
  27551. var BABYLON;
  27552. (function (BABYLON) {
  27553. var UniformBuffer = /** @class */ (function () {
  27554. /**
  27555. * Uniform buffer objects.
  27556. *
  27557. * Handles blocks of uniform on the GPU.
  27558. *
  27559. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27560. *
  27561. * For more information, please refer to :
  27562. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27563. */
  27564. function UniformBuffer(engine, data, dynamic) {
  27565. this._engine = engine;
  27566. this._noUBO = !engine.supportsUniformBuffers;
  27567. this._dynamic = dynamic;
  27568. this._data = data || [];
  27569. this._uniformLocations = {};
  27570. this._uniformSizes = {};
  27571. this._uniformLocationPointer = 0;
  27572. this._needSync = false;
  27573. if (this._noUBO) {
  27574. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27575. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27576. this.updateFloat = this._updateFloatForEffect;
  27577. this.updateFloat2 = this._updateFloat2ForEffect;
  27578. this.updateFloat3 = this._updateFloat3ForEffect;
  27579. this.updateFloat4 = this._updateFloat4ForEffect;
  27580. this.updateMatrix = this._updateMatrixForEffect;
  27581. this.updateVector3 = this._updateVector3ForEffect;
  27582. this.updateVector4 = this._updateVector4ForEffect;
  27583. this.updateColor3 = this._updateColor3ForEffect;
  27584. this.updateColor4 = this._updateColor4ForEffect;
  27585. }
  27586. else {
  27587. this._engine._uniformBuffers.push(this);
  27588. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27589. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27590. this.updateFloat = this._updateFloatForUniform;
  27591. this.updateFloat2 = this._updateFloat2ForUniform;
  27592. this.updateFloat3 = this._updateFloat3ForUniform;
  27593. this.updateFloat4 = this._updateFloat4ForUniform;
  27594. this.updateMatrix = this._updateMatrixForUniform;
  27595. this.updateVector3 = this._updateVector3ForUniform;
  27596. this.updateVector4 = this._updateVector4ForUniform;
  27597. this.updateColor3 = this._updateColor3ForUniform;
  27598. this.updateColor4 = this._updateColor4ForUniform;
  27599. }
  27600. }
  27601. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27602. // Properties
  27603. /**
  27604. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27605. * or just falling back on setUniformXXX calls.
  27606. */
  27607. get: function () {
  27608. return !this._noUBO;
  27609. },
  27610. enumerable: true,
  27611. configurable: true
  27612. });
  27613. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27614. /**
  27615. * Indicates if the WebGL underlying uniform buffer is in sync
  27616. * with the javascript cache data.
  27617. */
  27618. get: function () {
  27619. return !this._needSync;
  27620. },
  27621. enumerable: true,
  27622. configurable: true
  27623. });
  27624. /**
  27625. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27626. * Also, a dynamic UniformBuffer will disable cache verification and always
  27627. * update the underlying WebGL uniform buffer to the GPU.
  27628. */
  27629. UniformBuffer.prototype.isDynamic = function () {
  27630. return this._dynamic !== undefined;
  27631. };
  27632. /**
  27633. * The data cache on JS side.
  27634. */
  27635. UniformBuffer.prototype.getData = function () {
  27636. return this._bufferData;
  27637. };
  27638. /**
  27639. * The underlying WebGL Uniform buffer.
  27640. */
  27641. UniformBuffer.prototype.getBuffer = function () {
  27642. return this._buffer;
  27643. };
  27644. /**
  27645. * std140 layout specifies how to align data within an UBO structure.
  27646. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27647. * for specs.
  27648. */
  27649. UniformBuffer.prototype._fillAlignment = function (size) {
  27650. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27651. // and 4x4 matrices
  27652. // TODO : change if other types are used
  27653. var alignment;
  27654. if (size <= 2) {
  27655. alignment = size;
  27656. }
  27657. else {
  27658. alignment = 4;
  27659. }
  27660. if ((this._uniformLocationPointer % alignment) !== 0) {
  27661. var oldPointer = this._uniformLocationPointer;
  27662. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27663. var diff = this._uniformLocationPointer - oldPointer;
  27664. for (var i = 0; i < diff; i++) {
  27665. this._data.push(0);
  27666. }
  27667. }
  27668. };
  27669. /**
  27670. * Adds an uniform in the buffer.
  27671. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27672. * for the layout to be correct !
  27673. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27674. * @param {number|number[]} size Data size, or data directly.
  27675. */
  27676. UniformBuffer.prototype.addUniform = function (name, size) {
  27677. if (this._noUBO) {
  27678. return;
  27679. }
  27680. if (this._uniformLocations[name] !== undefined) {
  27681. // Already existing uniform
  27682. return;
  27683. }
  27684. // This function must be called in the order of the shader layout !
  27685. // size can be the size of the uniform, or data directly
  27686. var data;
  27687. if (size instanceof Array) {
  27688. data = size;
  27689. size = data.length;
  27690. }
  27691. else {
  27692. size = size;
  27693. data = [];
  27694. // Fill with zeros
  27695. for (var i = 0; i < size; i++) {
  27696. data.push(0);
  27697. }
  27698. }
  27699. this._fillAlignment(size);
  27700. this._uniformSizes[name] = size;
  27701. this._uniformLocations[name] = this._uniformLocationPointer;
  27702. this._uniformLocationPointer += size;
  27703. for (var i = 0; i < size; i++) {
  27704. this._data.push(data[i]);
  27705. }
  27706. this._needSync = true;
  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 {Matrix} mat A 4x4 matrix.
  27712. */
  27713. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27714. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27715. };
  27716. /**
  27717. * Wrapper for addUniform.
  27718. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27719. * @param {number} x
  27720. * @param {number} y
  27721. */
  27722. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27723. var temp = [x, y];
  27724. this.addUniform(name, temp);
  27725. };
  27726. /**
  27727. * Wrapper for addUniform.
  27728. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27729. * @param {number} x
  27730. * @param {number} y
  27731. * @param {number} z
  27732. */
  27733. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27734. var temp = [x, y, z];
  27735. this.addUniform(name, temp);
  27736. };
  27737. /**
  27738. * Wrapper for addUniform.
  27739. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27740. * @param {Color3} color
  27741. */
  27742. UniformBuffer.prototype.addColor3 = function (name, color) {
  27743. var temp = new Array();
  27744. color.toArray(temp);
  27745. this.addUniform(name, temp);
  27746. };
  27747. /**
  27748. * Wrapper for addUniform.
  27749. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27750. * @param {Color3} color
  27751. * @param {number} alpha
  27752. */
  27753. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27754. var temp = new Array();
  27755. color.toArray(temp);
  27756. temp.push(alpha);
  27757. this.addUniform(name, temp);
  27758. };
  27759. /**
  27760. * Wrapper for addUniform.
  27761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27762. * @param {Vector3} vector
  27763. */
  27764. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27765. var temp = new Array();
  27766. vector.toArray(temp);
  27767. this.addUniform(name, temp);
  27768. };
  27769. /**
  27770. * Wrapper for addUniform.
  27771. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27772. */
  27773. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27774. this.addUniform(name, 12);
  27775. };
  27776. /**
  27777. * Wrapper for addUniform.
  27778. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27779. */
  27780. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27781. this.addUniform(name, 8);
  27782. };
  27783. /**
  27784. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27785. */
  27786. UniformBuffer.prototype.create = function () {
  27787. if (this._noUBO) {
  27788. return;
  27789. }
  27790. if (this._buffer) {
  27791. return; // nothing to do
  27792. }
  27793. // See spec, alignment must be filled as a vec4
  27794. this._fillAlignment(4);
  27795. this._bufferData = new Float32Array(this._data);
  27796. this._rebuild();
  27797. this._needSync = true;
  27798. };
  27799. UniformBuffer.prototype._rebuild = function () {
  27800. if (this._noUBO) {
  27801. return;
  27802. }
  27803. if (this._dynamic) {
  27804. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27805. }
  27806. else {
  27807. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27808. }
  27809. };
  27810. /**
  27811. * Updates the WebGL Uniform Buffer on the GPU.
  27812. * If the `dynamic` flag is set to true, no cache comparison is done.
  27813. * Otherwise, the buffer will be updated only if the cache differs.
  27814. */
  27815. UniformBuffer.prototype.update = function () {
  27816. if (!this._buffer) {
  27817. this.create();
  27818. return;
  27819. }
  27820. if (!this._dynamic && !this._needSync) {
  27821. return;
  27822. }
  27823. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27824. this._needSync = false;
  27825. };
  27826. /**
  27827. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27828. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27829. * @param {number[]|Float32Array} data Flattened data
  27830. * @param {number} size Size of the data.
  27831. */
  27832. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27833. var location = this._uniformLocations[uniformName];
  27834. if (location === undefined) {
  27835. if (this._buffer) {
  27836. // Cannot add an uniform if the buffer is already created
  27837. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27838. return;
  27839. }
  27840. this.addUniform(uniformName, size);
  27841. location = this._uniformLocations[uniformName];
  27842. }
  27843. if (!this._buffer) {
  27844. this.create();
  27845. }
  27846. if (!this._dynamic) {
  27847. // Cache for static uniform buffers
  27848. var changed = false;
  27849. for (var i = 0; i < size; i++) {
  27850. if (this._bufferData[location + i] !== data[i]) {
  27851. changed = true;
  27852. this._bufferData[location + i] = data[i];
  27853. }
  27854. }
  27855. this._needSync = this._needSync || changed;
  27856. }
  27857. else {
  27858. // No cache for dynamic
  27859. for (var i = 0; i < size; i++) {
  27860. this._bufferData[location + i] = data[i];
  27861. }
  27862. }
  27863. };
  27864. // Update methods
  27865. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27866. // To match std140, matrix must be realigned
  27867. for (var i = 0; i < 3; i++) {
  27868. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27869. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27870. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27871. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27872. }
  27873. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27874. };
  27875. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27876. this._currentEffect.setMatrix3x3(name, matrix);
  27877. };
  27878. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27879. this._currentEffect.setMatrix2x2(name, matrix);
  27880. };
  27881. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27882. // To match std140, matrix must be realigned
  27883. for (var i = 0; i < 2; i++) {
  27884. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27885. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27886. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27887. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27888. }
  27889. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27890. };
  27891. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27892. this._currentEffect.setFloat(name, x);
  27893. };
  27894. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27895. UniformBuffer._tempBuffer[0] = x;
  27896. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27897. };
  27898. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27899. if (suffix === void 0) { suffix = ""; }
  27900. this._currentEffect.setFloat2(name + suffix, x, y);
  27901. };
  27902. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27903. if (suffix === void 0) { suffix = ""; }
  27904. UniformBuffer._tempBuffer[0] = x;
  27905. UniformBuffer._tempBuffer[1] = y;
  27906. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27907. };
  27908. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27909. if (suffix === void 0) { suffix = ""; }
  27910. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27911. };
  27912. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27913. if (suffix === void 0) { suffix = ""; }
  27914. UniformBuffer._tempBuffer[0] = x;
  27915. UniformBuffer._tempBuffer[1] = y;
  27916. UniformBuffer._tempBuffer[2] = z;
  27917. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27918. };
  27919. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27920. if (suffix === void 0) { suffix = ""; }
  27921. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27922. };
  27923. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27924. if (suffix === void 0) { suffix = ""; }
  27925. UniformBuffer._tempBuffer[0] = x;
  27926. UniformBuffer._tempBuffer[1] = y;
  27927. UniformBuffer._tempBuffer[2] = z;
  27928. UniformBuffer._tempBuffer[3] = w;
  27929. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27930. };
  27931. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27932. this._currentEffect.setMatrix(name, mat);
  27933. };
  27934. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27935. this.updateUniform(name, mat.toArray(), 16);
  27936. };
  27937. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27938. this._currentEffect.setVector3(name, vector);
  27939. };
  27940. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27941. vector.toArray(UniformBuffer._tempBuffer);
  27942. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27943. };
  27944. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27945. this._currentEffect.setVector4(name, vector);
  27946. };
  27947. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27948. vector.toArray(UniformBuffer._tempBuffer);
  27949. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27950. };
  27951. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27952. if (suffix === void 0) { suffix = ""; }
  27953. this._currentEffect.setColor3(name + suffix, color);
  27954. };
  27955. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27956. if (suffix === void 0) { suffix = ""; }
  27957. color.toArray(UniformBuffer._tempBuffer);
  27958. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27959. };
  27960. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27961. if (suffix === void 0) { suffix = ""; }
  27962. this._currentEffect.setColor4(name + suffix, color, alpha);
  27963. };
  27964. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27965. if (suffix === void 0) { suffix = ""; }
  27966. color.toArray(UniformBuffer._tempBuffer);
  27967. UniformBuffer._tempBuffer[3] = alpha;
  27968. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27969. };
  27970. /**
  27971. * Sets a sampler uniform on the effect.
  27972. * @param {string} name Name of the sampler.
  27973. * @param {Texture} texture
  27974. */
  27975. UniformBuffer.prototype.setTexture = function (name, texture) {
  27976. this._currentEffect.setTexture(name, texture);
  27977. };
  27978. /**
  27979. * Directly updates the value of the uniform in the cache AND on the GPU.
  27980. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27981. * @param {number[]|Float32Array} data Flattened data
  27982. */
  27983. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27984. this.updateUniform(uniformName, data, data.length);
  27985. this.update();
  27986. };
  27987. /**
  27988. * Binds this uniform buffer to an effect.
  27989. * @param {Effect} effect
  27990. * @param {string} name Name of the uniform block in the shader.
  27991. */
  27992. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27993. this._currentEffect = effect;
  27994. if (this._noUBO || !this._buffer) {
  27995. return;
  27996. }
  27997. effect.bindUniformBuffer(this._buffer, name);
  27998. };
  27999. /**
  28000. * Disposes the uniform buffer.
  28001. */
  28002. UniformBuffer.prototype.dispose = function () {
  28003. if (this._noUBO) {
  28004. return;
  28005. }
  28006. var index = this._engine._uniformBuffers.indexOf(this);
  28007. if (index !== -1) {
  28008. this._engine._uniformBuffers.splice(index, 1);
  28009. }
  28010. if (!this._buffer) {
  28011. return;
  28012. }
  28013. if (this._engine._releaseBuffer(this._buffer)) {
  28014. this._buffer = null;
  28015. }
  28016. };
  28017. // Pool for avoiding memory leaks
  28018. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28019. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28020. return UniformBuffer;
  28021. }());
  28022. BABYLON.UniformBuffer = UniformBuffer;
  28023. })(BABYLON || (BABYLON = {}));
  28024. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28025. var BABYLON;
  28026. (function (BABYLON) {
  28027. var PushMaterial = /** @class */ (function (_super) {
  28028. __extends(PushMaterial, _super);
  28029. function PushMaterial(name, scene) {
  28030. var _this = _super.call(this, name, scene) || this;
  28031. _this.storeEffectOnSubMeshes = true;
  28032. return _this;
  28033. }
  28034. PushMaterial.prototype.getEffect = function () {
  28035. return this._activeEffect;
  28036. };
  28037. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28038. if (!mesh) {
  28039. return false;
  28040. }
  28041. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28042. return true;
  28043. }
  28044. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28045. };
  28046. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28047. this._activeEffect.setMatrix("world", world);
  28048. };
  28049. PushMaterial.prototype.bind = function (world, mesh) {
  28050. if (!mesh) {
  28051. return;
  28052. }
  28053. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28054. };
  28055. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28056. if (effect === void 0) { effect = null; }
  28057. _super.prototype._afterBind.call(this, mesh);
  28058. this.getScene()._cachedEffect = effect;
  28059. };
  28060. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28061. if (visibility === void 0) { visibility = 1; }
  28062. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28063. };
  28064. return PushMaterial;
  28065. }(BABYLON.Material));
  28066. BABYLON.PushMaterial = PushMaterial;
  28067. })(BABYLON || (BABYLON = {}));
  28068. //# sourceMappingURL=babylon.pushMaterial.js.map
  28069. var BABYLON;
  28070. (function (BABYLON) {
  28071. var VertexData = /** @class */ (function () {
  28072. function VertexData() {
  28073. }
  28074. VertexData.prototype.set = function (data, kind) {
  28075. switch (kind) {
  28076. case BABYLON.VertexBuffer.PositionKind:
  28077. this.positions = data;
  28078. break;
  28079. case BABYLON.VertexBuffer.NormalKind:
  28080. this.normals = data;
  28081. break;
  28082. case BABYLON.VertexBuffer.TangentKind:
  28083. this.tangents = data;
  28084. break;
  28085. case BABYLON.VertexBuffer.UVKind:
  28086. this.uvs = data;
  28087. break;
  28088. case BABYLON.VertexBuffer.UV2Kind:
  28089. this.uvs2 = data;
  28090. break;
  28091. case BABYLON.VertexBuffer.UV3Kind:
  28092. this.uvs3 = data;
  28093. break;
  28094. case BABYLON.VertexBuffer.UV4Kind:
  28095. this.uvs4 = data;
  28096. break;
  28097. case BABYLON.VertexBuffer.UV5Kind:
  28098. this.uvs5 = data;
  28099. break;
  28100. case BABYLON.VertexBuffer.UV6Kind:
  28101. this.uvs6 = data;
  28102. break;
  28103. case BABYLON.VertexBuffer.ColorKind:
  28104. this.colors = data;
  28105. break;
  28106. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28107. this.matricesIndices = data;
  28108. break;
  28109. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28110. this.matricesWeights = data;
  28111. break;
  28112. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28113. this.matricesIndicesExtra = data;
  28114. break;
  28115. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28116. this.matricesWeightsExtra = data;
  28117. break;
  28118. }
  28119. };
  28120. /**
  28121. * Associates the vertexData to the passed Mesh.
  28122. * Sets it as updatable or not (default `false`).
  28123. * Returns the VertexData.
  28124. */
  28125. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28126. this._applyTo(mesh, updatable);
  28127. return this;
  28128. };
  28129. /**
  28130. * Associates the vertexData to the passed Geometry.
  28131. * Sets it as updatable or not (default `false`).
  28132. * Returns the VertexData.
  28133. */
  28134. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28135. this._applyTo(geometry, updatable);
  28136. return this;
  28137. };
  28138. /**
  28139. * Updates the associated mesh.
  28140. * Returns the VertexData.
  28141. */
  28142. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28143. this._update(mesh);
  28144. return this;
  28145. };
  28146. /**
  28147. * Updates the associated geometry.
  28148. * Returns the VertexData.
  28149. */
  28150. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28151. this._update(geometry);
  28152. return this;
  28153. };
  28154. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28155. if (updatable === void 0) { updatable = false; }
  28156. if (this.positions) {
  28157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28158. }
  28159. if (this.normals) {
  28160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28161. }
  28162. if (this.tangents) {
  28163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28164. }
  28165. if (this.uvs) {
  28166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28167. }
  28168. if (this.uvs2) {
  28169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28170. }
  28171. if (this.uvs3) {
  28172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28173. }
  28174. if (this.uvs4) {
  28175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28176. }
  28177. if (this.uvs5) {
  28178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28179. }
  28180. if (this.uvs6) {
  28181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28182. }
  28183. if (this.colors) {
  28184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28185. }
  28186. if (this.matricesIndices) {
  28187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28188. }
  28189. if (this.matricesWeights) {
  28190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28191. }
  28192. if (this.matricesIndicesExtra) {
  28193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28194. }
  28195. if (this.matricesWeightsExtra) {
  28196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28197. }
  28198. if (this.indices) {
  28199. meshOrGeometry.setIndices(this.indices, null, updatable);
  28200. }
  28201. return this;
  28202. };
  28203. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28204. if (this.positions) {
  28205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28206. }
  28207. if (this.normals) {
  28208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28209. }
  28210. if (this.tangents) {
  28211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28212. }
  28213. if (this.uvs) {
  28214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28215. }
  28216. if (this.uvs2) {
  28217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28218. }
  28219. if (this.uvs3) {
  28220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28221. }
  28222. if (this.uvs4) {
  28223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28224. }
  28225. if (this.uvs5) {
  28226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28227. }
  28228. if (this.uvs6) {
  28229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28230. }
  28231. if (this.colors) {
  28232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28233. }
  28234. if (this.matricesIndices) {
  28235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28236. }
  28237. if (this.matricesWeights) {
  28238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28239. }
  28240. if (this.matricesIndicesExtra) {
  28241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28242. }
  28243. if (this.matricesWeightsExtra) {
  28244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28245. }
  28246. if (this.indices) {
  28247. meshOrGeometry.setIndices(this.indices, null);
  28248. }
  28249. return this;
  28250. };
  28251. /**
  28252. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28253. * Returns the VertexData.
  28254. */
  28255. VertexData.prototype.transform = function (matrix) {
  28256. var transformed = BABYLON.Vector3.Zero();
  28257. var index;
  28258. if (this.positions) {
  28259. var position = BABYLON.Vector3.Zero();
  28260. for (index = 0; index < this.positions.length; index += 3) {
  28261. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28262. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28263. this.positions[index] = transformed.x;
  28264. this.positions[index + 1] = transformed.y;
  28265. this.positions[index + 2] = transformed.z;
  28266. }
  28267. }
  28268. if (this.normals) {
  28269. var normal = BABYLON.Vector3.Zero();
  28270. for (index = 0; index < this.normals.length; index += 3) {
  28271. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28272. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28273. this.normals[index] = transformed.x;
  28274. this.normals[index + 1] = transformed.y;
  28275. this.normals[index + 2] = transformed.z;
  28276. }
  28277. }
  28278. if (this.tangents) {
  28279. var tangent = BABYLON.Vector4.Zero();
  28280. var tangentTransformed = BABYLON.Vector4.Zero();
  28281. for (index = 0; index < this.tangents.length; index += 4) {
  28282. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28283. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28284. this.tangents[index] = tangentTransformed.x;
  28285. this.tangents[index + 1] = tangentTransformed.y;
  28286. this.tangents[index + 2] = tangentTransformed.z;
  28287. this.tangents[index + 3] = tangentTransformed.w;
  28288. }
  28289. }
  28290. return this;
  28291. };
  28292. /**
  28293. * Merges the passed VertexData into the current one.
  28294. * Returns the modified VertexData.
  28295. */
  28296. VertexData.prototype.merge = function (other, options) {
  28297. options = options || {};
  28298. if (other.indices) {
  28299. if (!this.indices) {
  28300. this.indices = [];
  28301. }
  28302. var offset = this.positions ? this.positions.length / 3 : 0;
  28303. for (var index = 0; index < other.indices.length; index++) {
  28304. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28305. this.indices.push(other.indices[index] + offset);
  28306. }
  28307. }
  28308. this.positions = this._mergeElement(this.positions, other.positions);
  28309. if (!this.positions) {
  28310. return this;
  28311. }
  28312. var count = this.positions.length / 3;
  28313. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28314. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28315. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28316. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28317. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28318. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28319. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28320. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28321. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28322. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28323. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28324. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28325. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28326. return this;
  28327. };
  28328. VertexData.prototype._mergeElement = function (source, other, length) {
  28329. if (length === void 0) { length = 0; }
  28330. if (!other && !source) {
  28331. return null;
  28332. }
  28333. if (!other) {
  28334. return this._mergeElement(source, new Float32Array(source.length), length);
  28335. }
  28336. if (!source) {
  28337. if (length === 0 || length === other.length) {
  28338. return other;
  28339. }
  28340. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28341. }
  28342. var len = other.length + source.length;
  28343. var isSrcTypedArray = source instanceof Float32Array;
  28344. var isOthTypedArray = other instanceof Float32Array;
  28345. // use non-loop method when the source is Float32Array
  28346. if (isSrcTypedArray) {
  28347. var ret32 = new Float32Array(len);
  28348. ret32.set(source);
  28349. ret32.set(other, source.length);
  28350. return ret32;
  28351. // source is number[], when other is also use concat
  28352. }
  28353. else if (!isOthTypedArray) {
  28354. return source.concat(other);
  28355. // source is a number[], but other is a Float32Array, loop required
  28356. }
  28357. else {
  28358. var ret = source.slice(0); // copy source to a separate array
  28359. for (var i = 0, len = other.length; i < len; i++) {
  28360. ret.push(other[i]);
  28361. }
  28362. return ret;
  28363. }
  28364. };
  28365. /**
  28366. * Serializes the VertexData.
  28367. * Returns a serialized object.
  28368. */
  28369. VertexData.prototype.serialize = function () {
  28370. var serializationObject = this.serialize();
  28371. if (this.positions) {
  28372. serializationObject.positions = this.positions;
  28373. }
  28374. if (this.normals) {
  28375. serializationObject.normals = this.normals;
  28376. }
  28377. if (this.tangents) {
  28378. serializationObject.tangents = this.tangents;
  28379. }
  28380. if (this.uvs) {
  28381. serializationObject.uvs = this.uvs;
  28382. }
  28383. if (this.uvs2) {
  28384. serializationObject.uvs2 = this.uvs2;
  28385. }
  28386. if (this.uvs3) {
  28387. serializationObject.uvs3 = this.uvs3;
  28388. }
  28389. if (this.uvs4) {
  28390. serializationObject.uvs4 = this.uvs4;
  28391. }
  28392. if (this.uvs5) {
  28393. serializationObject.uvs5 = this.uvs5;
  28394. }
  28395. if (this.uvs6) {
  28396. serializationObject.uvs6 = this.uvs6;
  28397. }
  28398. if (this.colors) {
  28399. serializationObject.colors = this.colors;
  28400. }
  28401. if (this.matricesIndices) {
  28402. serializationObject.matricesIndices = this.matricesIndices;
  28403. serializationObject.matricesIndices._isExpanded = true;
  28404. }
  28405. if (this.matricesWeights) {
  28406. serializationObject.matricesWeights = this.matricesWeights;
  28407. }
  28408. if (this.matricesIndicesExtra) {
  28409. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28410. serializationObject.matricesIndicesExtra._isExpanded = true;
  28411. }
  28412. if (this.matricesWeightsExtra) {
  28413. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28414. }
  28415. serializationObject.indices = this.indices;
  28416. return serializationObject;
  28417. };
  28418. // Statics
  28419. /**
  28420. * Returns the object VertexData associated to the passed mesh.
  28421. */
  28422. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28423. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28424. };
  28425. /**
  28426. * Returns the object VertexData associated to the passed geometry.
  28427. */
  28428. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28429. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28430. };
  28431. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28432. var result = new VertexData();
  28433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28434. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28435. }
  28436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28437. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28438. }
  28439. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28440. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28441. }
  28442. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28443. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28444. }
  28445. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28446. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28447. }
  28448. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28449. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28450. }
  28451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28452. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28453. }
  28454. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28455. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28456. }
  28457. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28458. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28459. }
  28460. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28461. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28462. }
  28463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28464. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28465. }
  28466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28467. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28468. }
  28469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28470. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28471. }
  28472. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28473. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28474. }
  28475. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28476. return result;
  28477. };
  28478. /**
  28479. * Creates the vertexData of the Ribbon.
  28480. */
  28481. VertexData.CreateRibbon = function (options) {
  28482. var pathArray = options.pathArray;
  28483. var closeArray = options.closeArray || false;
  28484. var closePath = options.closePath || false;
  28485. var invertUV = options.invertUV || false;
  28486. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28487. var offset = options.offset || defaultOffset;
  28488. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28489. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28490. var customUV = options.uvs;
  28491. var customColors = options.colors;
  28492. var positions = [];
  28493. var indices = [];
  28494. var normals = [];
  28495. var uvs = [];
  28496. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28497. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28498. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28499. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28500. var minlg; // minimal length among all paths from pathArray
  28501. var lg = []; // array of path lengths : nb of vertex per path
  28502. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28503. var p; // path iterator
  28504. var i; // point iterator
  28505. var j; // point iterator
  28506. // if single path in pathArray
  28507. if (pathArray.length < 2) {
  28508. var ar1 = [];
  28509. var ar2 = [];
  28510. for (i = 0; i < pathArray[0].length - offset; i++) {
  28511. ar1.push(pathArray[0][i]);
  28512. ar2.push(pathArray[0][i + offset]);
  28513. }
  28514. pathArray = [ar1, ar2];
  28515. }
  28516. // positions and horizontal distances (u)
  28517. var idc = 0;
  28518. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28519. var path;
  28520. var l;
  28521. minlg = pathArray[0].length;
  28522. var vectlg;
  28523. var dist;
  28524. for (p = 0; p < pathArray.length; p++) {
  28525. uTotalDistance[p] = 0;
  28526. us[p] = [0];
  28527. path = pathArray[p];
  28528. l = path.length;
  28529. minlg = (minlg < l) ? minlg : l;
  28530. j = 0;
  28531. while (j < l) {
  28532. positions.push(path[j].x, path[j].y, path[j].z);
  28533. if (j > 0) {
  28534. vectlg = path[j].subtract(path[j - 1]).length();
  28535. dist = vectlg + uTotalDistance[p];
  28536. us[p].push(dist);
  28537. uTotalDistance[p] = dist;
  28538. }
  28539. j++;
  28540. }
  28541. if (closePath) {
  28542. j--;
  28543. positions.push(path[0].x, path[0].y, path[0].z);
  28544. vectlg = path[j].subtract(path[0]).length();
  28545. dist = vectlg + uTotalDistance[p];
  28546. us[p].push(dist);
  28547. uTotalDistance[p] = dist;
  28548. }
  28549. lg[p] = l + closePathCorr;
  28550. idx[p] = idc;
  28551. idc += (l + closePathCorr);
  28552. }
  28553. // vertical distances (v)
  28554. var path1;
  28555. var path2;
  28556. var vertex1 = null;
  28557. var vertex2 = null;
  28558. for (i = 0; i < minlg + closePathCorr; i++) {
  28559. vTotalDistance[i] = 0;
  28560. vs[i] = [0];
  28561. for (p = 0; p < pathArray.length - 1; p++) {
  28562. path1 = pathArray[p];
  28563. path2 = pathArray[p + 1];
  28564. if (i === minlg) {
  28565. vertex1 = path1[0];
  28566. vertex2 = path2[0];
  28567. }
  28568. else {
  28569. vertex1 = path1[i];
  28570. vertex2 = path2[i];
  28571. }
  28572. vectlg = vertex2.subtract(vertex1).length();
  28573. dist = vectlg + vTotalDistance[i];
  28574. vs[i].push(dist);
  28575. vTotalDistance[i] = dist;
  28576. }
  28577. if (closeArray && vertex2 && vertex1) {
  28578. path1 = pathArray[p];
  28579. path2 = pathArray[0];
  28580. if (i === minlg) {
  28581. vertex2 = path2[0];
  28582. }
  28583. vectlg = vertex2.subtract(vertex1).length();
  28584. dist = vectlg + vTotalDistance[i];
  28585. vTotalDistance[i] = dist;
  28586. }
  28587. }
  28588. // uvs
  28589. var u;
  28590. var v;
  28591. if (customUV) {
  28592. for (p = 0; p < customUV.length; p++) {
  28593. uvs.push(customUV[p].x, customUV[p].y);
  28594. }
  28595. }
  28596. else {
  28597. for (p = 0; p < pathArray.length; p++) {
  28598. for (i = 0; i < minlg + closePathCorr; i++) {
  28599. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28600. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28601. if (invertUV) {
  28602. uvs.push(v, u);
  28603. }
  28604. else {
  28605. uvs.push(u, v);
  28606. }
  28607. }
  28608. }
  28609. }
  28610. // indices
  28611. p = 0; // path index
  28612. var pi = 0; // positions array index
  28613. var l1 = lg[p] - 1; // path1 length
  28614. var l2 = lg[p + 1] - 1; // path2 length
  28615. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28616. var shft = idx[1] - idx[0]; // shift
  28617. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28618. while (pi <= min && p < path1nb) {
  28619. // 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
  28620. indices.push(pi, pi + shft, pi + 1);
  28621. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28622. pi += 1;
  28623. if (pi === min) {
  28624. p++;
  28625. if (p === lg.length - 1) {
  28626. shft = idx[0] - idx[p];
  28627. l1 = lg[p] - 1;
  28628. l2 = lg[0] - 1;
  28629. }
  28630. else {
  28631. shft = idx[p + 1] - idx[p];
  28632. l1 = lg[p] - 1;
  28633. l2 = lg[p + 1] - 1;
  28634. }
  28635. pi = idx[p];
  28636. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28637. }
  28638. }
  28639. // normals
  28640. VertexData.ComputeNormals(positions, indices, normals);
  28641. if (closePath) {
  28642. var indexFirst = 0;
  28643. var indexLast = 0;
  28644. for (p = 0; p < pathArray.length; p++) {
  28645. indexFirst = idx[p] * 3;
  28646. if (p + 1 < pathArray.length) {
  28647. indexLast = (idx[p + 1] - 1) * 3;
  28648. }
  28649. else {
  28650. indexLast = normals.length - 3;
  28651. }
  28652. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28653. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28654. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28655. normals[indexLast] = normals[indexFirst];
  28656. normals[indexLast + 1] = normals[indexFirst + 1];
  28657. normals[indexLast + 2] = normals[indexFirst + 2];
  28658. }
  28659. }
  28660. // sides
  28661. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28662. // Colors
  28663. var colors = null;
  28664. if (customColors) {
  28665. colors = new Float32Array(customColors.length * 4);
  28666. for (var c = 0; c < customColors.length; c++) {
  28667. colors[c * 4] = customColors[c].r;
  28668. colors[c * 4 + 1] = customColors[c].g;
  28669. colors[c * 4 + 2] = customColors[c].b;
  28670. colors[c * 4 + 3] = customColors[c].a;
  28671. }
  28672. }
  28673. // Result
  28674. var vertexData = new VertexData();
  28675. var positions32 = new Float32Array(positions);
  28676. var normals32 = new Float32Array(normals);
  28677. var uvs32 = new Float32Array(uvs);
  28678. vertexData.indices = indices;
  28679. vertexData.positions = positions32;
  28680. vertexData.normals = normals32;
  28681. vertexData.uvs = uvs32;
  28682. if (colors) {
  28683. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28684. }
  28685. if (closePath) {
  28686. vertexData._idx = idx;
  28687. }
  28688. return vertexData;
  28689. };
  28690. /**
  28691. * Creates the VertexData of the Box.
  28692. */
  28693. VertexData.CreateBox = function (options) {
  28694. var normalsSource = [
  28695. new BABYLON.Vector3(0, 0, 1),
  28696. new BABYLON.Vector3(0, 0, -1),
  28697. new BABYLON.Vector3(1, 0, 0),
  28698. new BABYLON.Vector3(-1, 0, 0),
  28699. new BABYLON.Vector3(0, 1, 0),
  28700. new BABYLON.Vector3(0, -1, 0)
  28701. ];
  28702. var indices = [];
  28703. var positions = [];
  28704. var normals = [];
  28705. var uvs = [];
  28706. var width = options.width || options.size || 1;
  28707. var height = options.height || options.size || 1;
  28708. var depth = options.depth || options.size || 1;
  28709. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28710. var faceUV = options.faceUV || new Array(6);
  28711. var faceColors = options.faceColors;
  28712. var colors = [];
  28713. // default face colors and UV if undefined
  28714. for (var f = 0; f < 6; f++) {
  28715. if (faceUV[f] === undefined) {
  28716. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28717. }
  28718. if (faceColors && faceColors[f] === undefined) {
  28719. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28720. }
  28721. }
  28722. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28723. // Create each face in turn.
  28724. for (var index = 0; index < normalsSource.length; index++) {
  28725. var normal = normalsSource[index];
  28726. // Get two vectors perpendicular to the face normal and to each other.
  28727. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28728. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28729. // Six indices (two triangles) per face.
  28730. var verticesLength = positions.length / 3;
  28731. indices.push(verticesLength);
  28732. indices.push(verticesLength + 1);
  28733. indices.push(verticesLength + 2);
  28734. indices.push(verticesLength);
  28735. indices.push(verticesLength + 2);
  28736. indices.push(verticesLength + 3);
  28737. // Four vertices per face.
  28738. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28739. positions.push(vertex.x, vertex.y, vertex.z);
  28740. normals.push(normal.x, normal.y, normal.z);
  28741. uvs.push(faceUV[index].z, faceUV[index].w);
  28742. if (faceColors) {
  28743. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28744. }
  28745. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28746. positions.push(vertex.x, vertex.y, vertex.z);
  28747. normals.push(normal.x, normal.y, normal.z);
  28748. uvs.push(faceUV[index].x, faceUV[index].w);
  28749. if (faceColors) {
  28750. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28751. }
  28752. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28753. positions.push(vertex.x, vertex.y, vertex.z);
  28754. normals.push(normal.x, normal.y, normal.z);
  28755. uvs.push(faceUV[index].x, faceUV[index].y);
  28756. if (faceColors) {
  28757. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28758. }
  28759. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28760. positions.push(vertex.x, vertex.y, vertex.z);
  28761. normals.push(normal.x, normal.y, normal.z);
  28762. uvs.push(faceUV[index].z, faceUV[index].y);
  28763. if (faceColors) {
  28764. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28765. }
  28766. }
  28767. // sides
  28768. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28769. // Result
  28770. var vertexData = new VertexData();
  28771. vertexData.indices = indices;
  28772. vertexData.positions = positions;
  28773. vertexData.normals = normals;
  28774. vertexData.uvs = uvs;
  28775. if (faceColors) {
  28776. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28777. vertexData.colors = totalColors;
  28778. }
  28779. return vertexData;
  28780. };
  28781. /**
  28782. * Creates the VertexData of the Sphere.
  28783. */
  28784. VertexData.CreateSphere = function (options) {
  28785. var segments = options.segments || 32;
  28786. var diameterX = options.diameterX || options.diameter || 1;
  28787. var diameterY = options.diameterY || options.diameter || 1;
  28788. var diameterZ = options.diameterZ || options.diameter || 1;
  28789. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28790. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28791. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28792. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28793. var totalZRotationSteps = 2 + segments;
  28794. var totalYRotationSteps = 2 * totalZRotationSteps;
  28795. var indices = [];
  28796. var positions = [];
  28797. var normals = [];
  28798. var uvs = [];
  28799. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28800. var normalizedZ = zRotationStep / totalZRotationSteps;
  28801. var angleZ = normalizedZ * Math.PI * slice;
  28802. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28803. var normalizedY = yRotationStep / totalYRotationSteps;
  28804. var angleY = normalizedY * Math.PI * 2 * arc;
  28805. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28806. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28807. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28808. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28809. var vertex = complete.multiply(radius);
  28810. var normal = complete.divide(radius).normalize();
  28811. positions.push(vertex.x, vertex.y, vertex.z);
  28812. normals.push(normal.x, normal.y, normal.z);
  28813. uvs.push(normalizedY, normalizedZ);
  28814. }
  28815. if (zRotationStep > 0) {
  28816. var verticesCount = positions.length / 3;
  28817. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28818. indices.push((firstIndex));
  28819. indices.push((firstIndex + 1));
  28820. indices.push(firstIndex + totalYRotationSteps + 1);
  28821. indices.push((firstIndex + totalYRotationSteps + 1));
  28822. indices.push((firstIndex + 1));
  28823. indices.push((firstIndex + totalYRotationSteps + 2));
  28824. }
  28825. }
  28826. }
  28827. // Sides
  28828. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28829. // Result
  28830. var vertexData = new VertexData();
  28831. vertexData.indices = indices;
  28832. vertexData.positions = positions;
  28833. vertexData.normals = normals;
  28834. vertexData.uvs = uvs;
  28835. return vertexData;
  28836. };
  28837. /**
  28838. * Creates the VertexData of the Cylinder or Cone.
  28839. */
  28840. VertexData.CreateCylinder = function (options) {
  28841. var height = options.height || 2;
  28842. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28843. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28844. var tessellation = options.tessellation || 24;
  28845. var subdivisions = options.subdivisions || 1;
  28846. var hasRings = options.hasRings ? true : false;
  28847. var enclose = options.enclose ? true : false;
  28848. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28849. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28850. var faceUV = options.faceUV || new Array(3);
  28851. var faceColors = options.faceColors;
  28852. // default face colors and UV if undefined
  28853. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28854. var ringNb = (hasRings) ? subdivisions : 1;
  28855. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28856. var f;
  28857. for (f = 0; f < surfaceNb; f++) {
  28858. if (faceColors && faceColors[f] === undefined) {
  28859. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28860. }
  28861. }
  28862. for (f = 0; f < surfaceNb; f++) {
  28863. if (faceUV && faceUV[f] === undefined) {
  28864. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28865. }
  28866. }
  28867. var indices = new Array();
  28868. var positions = new Array();
  28869. var normals = new Array();
  28870. var uvs = new Array();
  28871. var colors = new Array();
  28872. var angle_step = Math.PI * 2 * arc / tessellation;
  28873. var angle;
  28874. var h;
  28875. var radius;
  28876. var tan = (diameterBottom - diameterTop) / 2 / height;
  28877. var ringVertex = BABYLON.Vector3.Zero();
  28878. var ringNormal = BABYLON.Vector3.Zero();
  28879. var ringFirstVertex = BABYLON.Vector3.Zero();
  28880. var ringFirstNormal = BABYLON.Vector3.Zero();
  28881. var quadNormal = BABYLON.Vector3.Zero();
  28882. var Y = BABYLON.Axis.Y;
  28883. // positions, normals, uvs
  28884. var i;
  28885. var j;
  28886. var r;
  28887. var ringIdx = 1;
  28888. var s = 1; // surface index
  28889. var cs = 0;
  28890. var v = 0;
  28891. for (i = 0; i <= subdivisions; i++) {
  28892. h = i / subdivisions;
  28893. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28894. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28895. for (r = 0; r < ringIdx; r++) {
  28896. if (hasRings) {
  28897. s += r;
  28898. }
  28899. if (enclose) {
  28900. s += 2 * r;
  28901. }
  28902. for (j = 0; j <= tessellation; j++) {
  28903. angle = j * angle_step;
  28904. // position
  28905. ringVertex.x = Math.cos(-angle) * radius;
  28906. ringVertex.y = -height / 2 + h * height;
  28907. ringVertex.z = Math.sin(-angle) * radius;
  28908. // normal
  28909. if (diameterTop === 0 && i === subdivisions) {
  28910. // if no top cap, reuse former normals
  28911. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28912. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28913. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28914. }
  28915. else {
  28916. ringNormal.x = ringVertex.x;
  28917. ringNormal.z = ringVertex.z;
  28918. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28919. ringNormal.normalize();
  28920. }
  28921. // keep first ring vertex values for enclose
  28922. if (j === 0) {
  28923. ringFirstVertex.copyFrom(ringVertex);
  28924. ringFirstNormal.copyFrom(ringNormal);
  28925. }
  28926. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28927. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28928. if (hasRings) {
  28929. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28930. }
  28931. else {
  28932. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28933. }
  28934. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28935. if (faceColors) {
  28936. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28937. }
  28938. }
  28939. // if enclose, add four vertices and their dedicated normals
  28940. if (arc !== 1 && enclose) {
  28941. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28942. positions.push(0, ringVertex.y, 0);
  28943. positions.push(0, ringVertex.y, 0);
  28944. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28945. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28946. quadNormal.normalize();
  28947. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28948. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28949. quadNormal.normalize();
  28950. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28951. if (hasRings) {
  28952. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28953. }
  28954. else {
  28955. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28956. }
  28957. uvs.push(faceUV[s + 1].x, v);
  28958. uvs.push(faceUV[s + 1].z, v);
  28959. if (hasRings) {
  28960. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28961. }
  28962. else {
  28963. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28964. }
  28965. uvs.push(faceUV[s + 2].x, v);
  28966. uvs.push(faceUV[s + 2].z, v);
  28967. if (faceColors) {
  28968. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28969. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28970. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28971. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28972. }
  28973. }
  28974. if (cs !== s) {
  28975. cs = s;
  28976. }
  28977. }
  28978. }
  28979. // indices
  28980. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28981. var s;
  28982. i = 0;
  28983. for (s = 0; s < subdivisions; s++) {
  28984. var i0 = 0;
  28985. var i1 = 0;
  28986. var i2 = 0;
  28987. var i3 = 0;
  28988. for (j = 0; j < tessellation; j++) {
  28989. i0 = i * (e + 1) + j;
  28990. i1 = (i + 1) * (e + 1) + j;
  28991. i2 = i * (e + 1) + (j + 1);
  28992. i3 = (i + 1) * (e + 1) + (j + 1);
  28993. indices.push(i0, i1, i2);
  28994. indices.push(i3, i2, i1);
  28995. }
  28996. if (arc !== 1 && enclose) {
  28997. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28998. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28999. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29000. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29001. }
  29002. i = (hasRings) ? (i + 2) : (i + 1);
  29003. }
  29004. // Caps
  29005. var createCylinderCap = function (isTop) {
  29006. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29007. if (radius === 0) {
  29008. return;
  29009. }
  29010. // Cap positions, normals & uvs
  29011. var angle;
  29012. var circleVector;
  29013. var i;
  29014. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29015. var c = null;
  29016. if (faceColors) {
  29017. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29018. }
  29019. // cap center
  29020. var vbase = positions.length / 3;
  29021. var offset = isTop ? height / 2 : -height / 2;
  29022. var center = new BABYLON.Vector3(0, offset, 0);
  29023. positions.push(center.x, center.y, center.z);
  29024. normals.push(0, isTop ? 1 : -1, 0);
  29025. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29026. if (c) {
  29027. colors.push(c.r, c.g, c.b, c.a);
  29028. }
  29029. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29030. for (i = 0; i <= tessellation; i++) {
  29031. angle = Math.PI * 2 * i * arc / tessellation;
  29032. var cos = Math.cos(-angle);
  29033. var sin = Math.sin(-angle);
  29034. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29035. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29036. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29037. normals.push(0, isTop ? 1 : -1, 0);
  29038. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29039. if (c) {
  29040. colors.push(c.r, c.g, c.b, c.a);
  29041. }
  29042. }
  29043. // Cap indices
  29044. for (i = 0; i < tessellation; i++) {
  29045. if (!isTop) {
  29046. indices.push(vbase);
  29047. indices.push(vbase + (i + 1));
  29048. indices.push(vbase + (i + 2));
  29049. }
  29050. else {
  29051. indices.push(vbase);
  29052. indices.push(vbase + (i + 2));
  29053. indices.push(vbase + (i + 1));
  29054. }
  29055. }
  29056. };
  29057. // add caps to geometry
  29058. createCylinderCap(false);
  29059. createCylinderCap(true);
  29060. // Sides
  29061. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29062. var vertexData = new VertexData();
  29063. vertexData.indices = indices;
  29064. vertexData.positions = positions;
  29065. vertexData.normals = normals;
  29066. vertexData.uvs = uvs;
  29067. if (faceColors) {
  29068. vertexData.colors = colors;
  29069. }
  29070. return vertexData;
  29071. };
  29072. /**
  29073. * Creates the VertexData of the Torus.
  29074. */
  29075. VertexData.CreateTorus = function (options) {
  29076. var indices = [];
  29077. var positions = [];
  29078. var normals = [];
  29079. var uvs = [];
  29080. var diameter = options.diameter || 1;
  29081. var thickness = options.thickness || 0.5;
  29082. var tessellation = options.tessellation || 16;
  29083. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29084. var stride = tessellation + 1;
  29085. for (var i = 0; i <= tessellation; i++) {
  29086. var u = i / tessellation;
  29087. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29088. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29089. for (var j = 0; j <= tessellation; j++) {
  29090. var v = 1 - j / tessellation;
  29091. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29092. var dx = Math.cos(innerAngle);
  29093. var dy = Math.sin(innerAngle);
  29094. // Create a vertex.
  29095. var normal = new BABYLON.Vector3(dx, dy, 0);
  29096. var position = normal.scale(thickness / 2);
  29097. var textureCoordinate = new BABYLON.Vector2(u, v);
  29098. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29099. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29100. positions.push(position.x, position.y, position.z);
  29101. normals.push(normal.x, normal.y, normal.z);
  29102. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29103. // And create indices for two triangles.
  29104. var nextI = (i + 1) % stride;
  29105. var nextJ = (j + 1) % stride;
  29106. indices.push(i * stride + j);
  29107. indices.push(i * stride + nextJ);
  29108. indices.push(nextI * stride + j);
  29109. indices.push(i * stride + nextJ);
  29110. indices.push(nextI * stride + nextJ);
  29111. indices.push(nextI * stride + j);
  29112. }
  29113. }
  29114. // Sides
  29115. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29116. // Result
  29117. var vertexData = new VertexData();
  29118. vertexData.indices = indices;
  29119. vertexData.positions = positions;
  29120. vertexData.normals = normals;
  29121. vertexData.uvs = uvs;
  29122. return vertexData;
  29123. };
  29124. /**
  29125. * Creates the VertexData of the LineSystem.
  29126. */
  29127. VertexData.CreateLineSystem = function (options) {
  29128. var indices = [];
  29129. var positions = [];
  29130. var lines = options.lines;
  29131. var idx = 0;
  29132. for (var l = 0; l < lines.length; l++) {
  29133. var points = lines[l];
  29134. for (var index = 0; index < points.length; index++) {
  29135. positions.push(points[index].x, points[index].y, points[index].z);
  29136. if (index > 0) {
  29137. indices.push(idx - 1);
  29138. indices.push(idx);
  29139. }
  29140. idx++;
  29141. }
  29142. }
  29143. var vertexData = new VertexData();
  29144. vertexData.indices = indices;
  29145. vertexData.positions = positions;
  29146. return vertexData;
  29147. };
  29148. /**
  29149. * Create the VertexData of the DashedLines.
  29150. */
  29151. VertexData.CreateDashedLines = function (options) {
  29152. var dashSize = options.dashSize || 3;
  29153. var gapSize = options.gapSize || 1;
  29154. var dashNb = options.dashNb || 200;
  29155. var points = options.points;
  29156. var positions = new Array();
  29157. var indices = new Array();
  29158. var curvect = BABYLON.Vector3.Zero();
  29159. var lg = 0;
  29160. var nb = 0;
  29161. var shft = 0;
  29162. var dashshft = 0;
  29163. var curshft = 0;
  29164. var idx = 0;
  29165. var i = 0;
  29166. for (i = 0; i < points.length - 1; i++) {
  29167. points[i + 1].subtractToRef(points[i], curvect);
  29168. lg += curvect.length();
  29169. }
  29170. shft = lg / dashNb;
  29171. dashshft = dashSize * shft / (dashSize + gapSize);
  29172. for (i = 0; i < points.length - 1; i++) {
  29173. points[i + 1].subtractToRef(points[i], curvect);
  29174. nb = Math.floor(curvect.length() / shft);
  29175. curvect.normalize();
  29176. for (var j = 0; j < nb; j++) {
  29177. curshft = shft * j;
  29178. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29179. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29180. indices.push(idx, idx + 1);
  29181. idx += 2;
  29182. }
  29183. }
  29184. // Result
  29185. var vertexData = new VertexData();
  29186. vertexData.positions = positions;
  29187. vertexData.indices = indices;
  29188. return vertexData;
  29189. };
  29190. /**
  29191. * Creates the VertexData of the Ground.
  29192. */
  29193. VertexData.CreateGround = function (options) {
  29194. var indices = [];
  29195. var positions = [];
  29196. var normals = [];
  29197. var uvs = [];
  29198. var row, col;
  29199. var width = options.width || 1;
  29200. var height = options.height || 1;
  29201. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29202. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29203. for (row = 0; row <= subdivisionsY; row++) {
  29204. for (col = 0; col <= subdivisionsX; col++) {
  29205. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29206. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29207. positions.push(position.x, position.y, position.z);
  29208. normals.push(normal.x, normal.y, normal.z);
  29209. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29210. }
  29211. }
  29212. for (row = 0; row < subdivisionsY; row++) {
  29213. for (col = 0; col < subdivisionsX; col++) {
  29214. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29215. indices.push(col + 1 + row * (subdivisionsX + 1));
  29216. indices.push(col + row * (subdivisionsX + 1));
  29217. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29218. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29219. indices.push(col + row * (subdivisionsX + 1));
  29220. }
  29221. }
  29222. // Result
  29223. var vertexData = new VertexData();
  29224. vertexData.indices = indices;
  29225. vertexData.positions = positions;
  29226. vertexData.normals = normals;
  29227. vertexData.uvs = uvs;
  29228. return vertexData;
  29229. };
  29230. /**
  29231. * Creates the VertexData of the TiledGround.
  29232. */
  29233. VertexData.CreateTiledGround = function (options) {
  29234. var xmin = options.xmin || -1.0;
  29235. var zmin = options.zmin || -1.0;
  29236. var xmax = options.xmax || 1.0;
  29237. var zmax = options.zmax || 1.0;
  29238. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29239. var precision = options.precision || { w: 1, h: 1 };
  29240. var indices = new Array();
  29241. var positions = new Array();
  29242. var normals = new Array();
  29243. var uvs = new Array();
  29244. var row, col, tileRow, tileCol;
  29245. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29246. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29247. precision.w = (precision.w < 1) ? 1 : precision.w;
  29248. precision.h = (precision.h < 1) ? 1 : precision.h;
  29249. var tileSize = {
  29250. 'w': (xmax - xmin) / subdivisions.w,
  29251. 'h': (zmax - zmin) / subdivisions.h
  29252. };
  29253. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29254. // Indices
  29255. var base = positions.length / 3;
  29256. var rowLength = precision.w + 1;
  29257. for (row = 0; row < precision.h; row++) {
  29258. for (col = 0; col < precision.w; col++) {
  29259. var square = [
  29260. base + col + row * rowLength,
  29261. base + (col + 1) + row * rowLength,
  29262. base + (col + 1) + (row + 1) * rowLength,
  29263. base + col + (row + 1) * rowLength
  29264. ];
  29265. indices.push(square[1]);
  29266. indices.push(square[2]);
  29267. indices.push(square[3]);
  29268. indices.push(square[0]);
  29269. indices.push(square[1]);
  29270. indices.push(square[3]);
  29271. }
  29272. }
  29273. // Position, normals and uvs
  29274. var position = BABYLON.Vector3.Zero();
  29275. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29276. for (row = 0; row <= precision.h; row++) {
  29277. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29278. for (col = 0; col <= precision.w; col++) {
  29279. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29280. position.y = 0;
  29281. positions.push(position.x, position.y, position.z);
  29282. normals.push(normal.x, normal.y, normal.z);
  29283. uvs.push(col / precision.w, row / precision.h);
  29284. }
  29285. }
  29286. }
  29287. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29288. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29289. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29290. }
  29291. }
  29292. // Result
  29293. var vertexData = new VertexData();
  29294. vertexData.indices = indices;
  29295. vertexData.positions = positions;
  29296. vertexData.normals = normals;
  29297. vertexData.uvs = uvs;
  29298. return vertexData;
  29299. };
  29300. /**
  29301. * Creates the VertexData of the Ground designed from a heightmap.
  29302. */
  29303. VertexData.CreateGroundFromHeightMap = function (options) {
  29304. var indices = [];
  29305. var positions = [];
  29306. var normals = [];
  29307. var uvs = [];
  29308. var row, col;
  29309. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29310. // Vertices
  29311. for (row = 0; row <= options.subdivisions; row++) {
  29312. for (col = 0; col <= options.subdivisions; col++) {
  29313. 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));
  29314. // Compute height
  29315. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29316. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29317. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29318. var r = options.buffer[pos] / 255.0;
  29319. var g = options.buffer[pos + 1] / 255.0;
  29320. var b = options.buffer[pos + 2] / 255.0;
  29321. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29322. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29323. // Add vertex
  29324. positions.push(position.x, position.y, position.z);
  29325. normals.push(0, 0, 0);
  29326. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29327. }
  29328. }
  29329. // Indices
  29330. for (row = 0; row < options.subdivisions; row++) {
  29331. for (col = 0; col < options.subdivisions; col++) {
  29332. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29333. indices.push(col + 1 + row * (options.subdivisions + 1));
  29334. indices.push(col + row * (options.subdivisions + 1));
  29335. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29336. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29337. indices.push(col + row * (options.subdivisions + 1));
  29338. }
  29339. }
  29340. // Normals
  29341. VertexData.ComputeNormals(positions, indices, normals);
  29342. // Result
  29343. var vertexData = new VertexData();
  29344. vertexData.indices = indices;
  29345. vertexData.positions = positions;
  29346. vertexData.normals = normals;
  29347. vertexData.uvs = uvs;
  29348. return vertexData;
  29349. };
  29350. /**
  29351. * Creates the VertexData of the Plane.
  29352. */
  29353. VertexData.CreatePlane = function (options) {
  29354. var indices = [];
  29355. var positions = [];
  29356. var normals = [];
  29357. var uvs = [];
  29358. var width = options.width || options.size || 1;
  29359. var height = options.height || options.size || 1;
  29360. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29361. // Vertices
  29362. var halfWidth = width / 2.0;
  29363. var halfHeight = height / 2.0;
  29364. positions.push(-halfWidth, -halfHeight, 0);
  29365. normals.push(0, 0, -1.0);
  29366. uvs.push(0.0, 0.0);
  29367. positions.push(halfWidth, -halfHeight, 0);
  29368. normals.push(0, 0, -1.0);
  29369. uvs.push(1.0, 0.0);
  29370. positions.push(halfWidth, halfHeight, 0);
  29371. normals.push(0, 0, -1.0);
  29372. uvs.push(1.0, 1.0);
  29373. positions.push(-halfWidth, halfHeight, 0);
  29374. normals.push(0, 0, -1.0);
  29375. uvs.push(0.0, 1.0);
  29376. // Indices
  29377. indices.push(0);
  29378. indices.push(1);
  29379. indices.push(2);
  29380. indices.push(0);
  29381. indices.push(2);
  29382. indices.push(3);
  29383. // Sides
  29384. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29385. // Result
  29386. var vertexData = new VertexData();
  29387. vertexData.indices = indices;
  29388. vertexData.positions = positions;
  29389. vertexData.normals = normals;
  29390. vertexData.uvs = uvs;
  29391. return vertexData;
  29392. };
  29393. /**
  29394. * Creates the VertexData of the Disc or regular Polygon.
  29395. */
  29396. VertexData.CreateDisc = function (options) {
  29397. var positions = new Array();
  29398. var indices = new Array();
  29399. var normals = new Array();
  29400. var uvs = new Array();
  29401. var radius = options.radius || 0.5;
  29402. var tessellation = options.tessellation || 64;
  29403. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29404. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29405. // positions and uvs
  29406. positions.push(0, 0, 0); // disc center first
  29407. uvs.push(0.5, 0.5);
  29408. var theta = Math.PI * 2 * arc;
  29409. var step = theta / tessellation;
  29410. for (var a = 0; a < theta; a += step) {
  29411. var x = Math.cos(a);
  29412. var y = Math.sin(a);
  29413. var u = (x + 1) / 2;
  29414. var v = (1 - y) / 2;
  29415. positions.push(radius * x, radius * y, 0);
  29416. uvs.push(u, v);
  29417. }
  29418. if (arc === 1) {
  29419. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29420. uvs.push(uvs[2], uvs[3]);
  29421. }
  29422. //indices
  29423. var vertexNb = positions.length / 3;
  29424. for (var i = 1; i < vertexNb - 1; i++) {
  29425. indices.push(i + 1, 0, i);
  29426. }
  29427. // result
  29428. VertexData.ComputeNormals(positions, indices, normals);
  29429. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29430. var vertexData = new VertexData();
  29431. vertexData.indices = indices;
  29432. vertexData.positions = positions;
  29433. vertexData.normals = normals;
  29434. vertexData.uvs = uvs;
  29435. return vertexData;
  29436. };
  29437. /**
  29438. * Re-creates the VertexData of the Polygon for sideOrientation.
  29439. */
  29440. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29441. var faceUV = fUV || new Array(3);
  29442. var faceColors = fColors;
  29443. var colors = [];
  29444. // default face colors and UV if undefined
  29445. for (var f = 0; f < 3; f++) {
  29446. if (faceUV[f] === undefined) {
  29447. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29448. }
  29449. if (faceColors && faceColors[f] === undefined) {
  29450. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29451. }
  29452. }
  29453. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29454. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29455. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29456. var indices = polygon.getIndices();
  29457. // set face colours and textures
  29458. var idx = 0;
  29459. var face = 0;
  29460. for (var index = 0; index < normals.length; index += 3) {
  29461. //Edge Face no. 1
  29462. if (Math.abs(normals[index + 1]) < 0.001) {
  29463. face = 1;
  29464. }
  29465. //Top Face no. 0
  29466. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29467. face = 0;
  29468. }
  29469. //Bottom Face no. 2
  29470. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29471. face = 2;
  29472. }
  29473. idx = index / 3;
  29474. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29475. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29476. if (faceColors) {
  29477. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29478. }
  29479. }
  29480. // sides
  29481. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29482. // Result
  29483. var vertexData = new VertexData();
  29484. vertexData.indices = indices;
  29485. vertexData.positions = positions;
  29486. vertexData.normals = normals;
  29487. vertexData.uvs = uvs;
  29488. if (faceColors) {
  29489. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29490. vertexData.colors = totalColors;
  29491. }
  29492. return vertexData;
  29493. };
  29494. /**
  29495. * Creates the VertexData of the IcoSphere.
  29496. */
  29497. VertexData.CreateIcoSphere = function (options) {
  29498. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29499. var radius = options.radius || 1;
  29500. var flat = (options.flat === undefined) ? true : options.flat;
  29501. var subdivisions = options.subdivisions || 4;
  29502. var radiusX = options.radiusX || radius;
  29503. var radiusY = options.radiusY || radius;
  29504. var radiusZ = options.radiusZ || radius;
  29505. var t = (1 + Math.sqrt(5)) / 2;
  29506. // 12 vertex x,y,z
  29507. var ico_vertices = [
  29508. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29509. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29510. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29511. ];
  29512. // index of 3 vertex makes a face of icopshere
  29513. var ico_indices = [
  29514. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29515. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29516. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29517. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29518. ];
  29519. // vertex for uv have aliased position, not for UV
  29520. var vertices_unalias_id = [
  29521. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29522. // vertex alias
  29523. 0,
  29524. 2,
  29525. 3,
  29526. 3,
  29527. 3,
  29528. 4,
  29529. 7,
  29530. 8,
  29531. 9,
  29532. 9,
  29533. 10,
  29534. 11 // 23: B + 12
  29535. ];
  29536. // uv as integer step (not pixels !)
  29537. var ico_vertexuv = [
  29538. 5, 1, 3, 1, 6, 4, 0, 0,
  29539. 5, 3, 4, 2, 2, 2, 4, 0,
  29540. 2, 0, 1, 1, 6, 0, 6, 2,
  29541. // vertex alias (for same vertex on different faces)
  29542. 0, 4,
  29543. 3, 3,
  29544. 4, 4,
  29545. 3, 1,
  29546. 4, 2,
  29547. 4, 4,
  29548. 0, 2,
  29549. 1, 1,
  29550. 2, 2,
  29551. 3, 3,
  29552. 1, 3,
  29553. 2, 4 // 23: B + 12
  29554. ];
  29555. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29556. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29557. // First island of uv mapping
  29558. // v = 4h 3+ 2
  29559. // v = 3h 9+ 4
  29560. // v = 2h 9+ 5 B
  29561. // v = 1h 9 1 0
  29562. // v = 0h 3 8 7 A
  29563. // u = 0 1 2 3 4 5 6 *a
  29564. // Second island of uv mapping
  29565. // v = 4h 0+ B+ 4+
  29566. // v = 3h A+ 2+
  29567. // v = 2h 7+ 6 3+
  29568. // v = 1h 8+ 3+
  29569. // v = 0h
  29570. // u = 0 1 2 3 4 5 6 *a
  29571. // Face layout on texture UV mapping
  29572. // ============
  29573. // \ 4 /\ 16 / ======
  29574. // \ / \ / /\ 11 /
  29575. // \/ 7 \/ / \ /
  29576. // ======= / 10 \/
  29577. // /\ 17 /\ =======
  29578. // / \ / \ \ 15 /\
  29579. // / 8 \/ 12 \ \ / \
  29580. // ============ \/ 6 \
  29581. // \ 18 /\ ============
  29582. // \ / \ \ 5 /\ 0 /
  29583. // \/ 13 \ \ / \ /
  29584. // ======= \/ 1 \/
  29585. // =============
  29586. // /\ 19 /\ 2 /\
  29587. // / \ / \ / \
  29588. // / 14 \/ 9 \/ 3 \
  29589. // ===================
  29590. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29591. var ustep = 138 / 1024;
  29592. var vstep = 239 / 1024;
  29593. var uoffset = 60 / 1024;
  29594. var voffset = 26 / 1024;
  29595. // Second island should have margin, not to touch the first island
  29596. // avoid any borderline artefact in pixel rounding
  29597. var island_u_offset = -40 / 1024;
  29598. var island_v_offset = +20 / 1024;
  29599. // face is either island 0 or 1 :
  29600. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29601. var island = [
  29602. 0, 0, 0, 0, 1,
  29603. 0, 0, 1, 1, 0,
  29604. 0, 0, 1, 1, 0,
  29605. 0, 1, 1, 1, 0 // 15 - 19
  29606. ];
  29607. var indices = new Array();
  29608. var positions = new Array();
  29609. var normals = new Array();
  29610. var uvs = new Array();
  29611. var current_indice = 0;
  29612. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29613. var face_vertex_pos = new Array(3);
  29614. var face_vertex_uv = new Array(3);
  29615. var v012;
  29616. for (v012 = 0; v012 < 3; v012++) {
  29617. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29618. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29619. }
  29620. // create all with normals
  29621. for (var face = 0; face < 20; face++) {
  29622. // 3 vertex per face
  29623. for (v012 = 0; v012 < 3; v012++) {
  29624. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29625. var v_id = ico_indices[3 * face + v012];
  29626. // vertex have 3D position (x,y,z)
  29627. 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]);
  29628. // Normalize to get normal, then scale to radius
  29629. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29630. // uv Coordinates from vertex ID
  29631. 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);
  29632. }
  29633. // Subdivide the face (interpolate pos, norm, uv)
  29634. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29635. // - norm is linear interpolation of vertex corner normal
  29636. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29637. // - uv is linear interpolation
  29638. //
  29639. // Topology is as below for sub-divide by 2
  29640. // vertex shown as v0,v1,v2
  29641. // interp index is i1 to progress in range [v0,v1[
  29642. // interp index is i2 to progress in range [v0,v2[
  29643. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29644. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29645. //
  29646. //
  29647. // i2 v2
  29648. // ^ ^
  29649. // / / \
  29650. // / / \
  29651. // / / \
  29652. // / / (0,1) \
  29653. // / #---------\
  29654. // / / \ (0,0)'/ \
  29655. // / / \ / \
  29656. // / / \ / \
  29657. // / / (0,0) \ / (1,0) \
  29658. // / #---------#---------\
  29659. // v0 v1
  29660. //
  29661. // --------------------> i1
  29662. //
  29663. // interp of (i1,i2):
  29664. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29665. // along i1 : lerp(x0,x1, i1/(S-i2))
  29666. //
  29667. // centroid of triangle is needed to get help normal computation
  29668. // (c1,c2) are used for centroid location
  29669. var interp_vertex = function (i1, i2, c1, c2) {
  29670. // vertex is interpolated from
  29671. // - face_vertex_pos[0..2]
  29672. // - face_vertex_uv[0..2]
  29673. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29674. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29675. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29676. pos_interp.normalize();
  29677. var vertex_normal;
  29678. if (flat) {
  29679. // in flat mode, recalculate normal as face centroid normal
  29680. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29681. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29682. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29683. }
  29684. else {
  29685. // in smooth mode, recalculate normal from each single vertex position
  29686. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29687. }
  29688. // Vertex normal need correction due to X,Y,Z radius scaling
  29689. vertex_normal.x /= radiusX;
  29690. vertex_normal.y /= radiusY;
  29691. vertex_normal.z /= radiusZ;
  29692. vertex_normal.normalize();
  29693. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29694. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29695. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29696. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29697. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29698. uvs.push(uv_interp.x, uv_interp.y);
  29699. // push each vertex has member of a face
  29700. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29701. indices.push(current_indice);
  29702. current_indice++;
  29703. };
  29704. for (var i2 = 0; i2 < subdivisions; i2++) {
  29705. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29706. // face : (i1,i2) for /\ :
  29707. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29708. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29709. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29710. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29711. if (i1 + i2 + 1 < subdivisions) {
  29712. // face : (i1,i2)' for \/ :
  29713. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29714. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29715. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29716. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29717. }
  29718. }
  29719. }
  29720. }
  29721. // Sides
  29722. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29723. // Result
  29724. var vertexData = new VertexData();
  29725. vertexData.indices = indices;
  29726. vertexData.positions = positions;
  29727. vertexData.normals = normals;
  29728. vertexData.uvs = uvs;
  29729. return vertexData;
  29730. };
  29731. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29732. /**
  29733. * Creates the VertexData of the Polyhedron.
  29734. */
  29735. VertexData.CreatePolyhedron = function (options) {
  29736. // provided polyhedron types :
  29737. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29738. // 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)
  29739. var polyhedra = [];
  29740. 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]] };
  29741. 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]] };
  29742. polyhedra[2] = {
  29743. 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]],
  29744. 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]]
  29745. };
  29746. polyhedra[3] = {
  29747. 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]],
  29748. 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]]
  29749. };
  29750. polyhedra[4] = {
  29751. 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]],
  29752. 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]]
  29753. };
  29754. 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]] };
  29755. 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]] };
  29756. 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]] };
  29757. 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]] };
  29758. 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]] };
  29759. 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]] };
  29760. 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]] };
  29761. 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]] };
  29762. 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]] };
  29763. polyhedra[14] = {
  29764. 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]],
  29765. 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]]
  29766. };
  29767. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29768. var size = options.size;
  29769. var sizeX = options.sizeX || size || 1;
  29770. var sizeY = options.sizeY || size || 1;
  29771. var sizeZ = options.sizeZ || size || 1;
  29772. var data = options.custom || polyhedra[type];
  29773. var nbfaces = data.face.length;
  29774. var faceUV = options.faceUV || new Array(nbfaces);
  29775. var faceColors = options.faceColors;
  29776. var flat = (options.flat === undefined) ? true : options.flat;
  29777. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29778. var positions = new Array();
  29779. var indices = new Array();
  29780. var normals = new Array();
  29781. var uvs = new Array();
  29782. var colors = new Array();
  29783. var index = 0;
  29784. var faceIdx = 0; // face cursor in the array "indexes"
  29785. var indexes = new Array();
  29786. var i = 0;
  29787. var f = 0;
  29788. var u, v, ang, x, y, tmp;
  29789. // default face colors and UV if undefined
  29790. if (flat) {
  29791. for (f = 0; f < nbfaces; f++) {
  29792. if (faceColors && faceColors[f] === undefined) {
  29793. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29794. }
  29795. if (faceUV && faceUV[f] === undefined) {
  29796. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29797. }
  29798. }
  29799. }
  29800. if (!flat) {
  29801. for (i = 0; i < data.vertex.length; i++) {
  29802. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29803. uvs.push(0, 0);
  29804. }
  29805. for (f = 0; f < nbfaces; f++) {
  29806. for (i = 0; i < data.face[f].length - 2; i++) {
  29807. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29808. }
  29809. }
  29810. }
  29811. else {
  29812. for (f = 0; f < nbfaces; f++) {
  29813. var fl = data.face[f].length; // number of vertices of the current face
  29814. ang = 2 * Math.PI / fl;
  29815. x = 0.5 * Math.tan(ang / 2);
  29816. y = 0.5;
  29817. // positions, uvs, colors
  29818. for (i = 0; i < fl; i++) {
  29819. // positions
  29820. 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);
  29821. indexes.push(index);
  29822. index++;
  29823. // uvs
  29824. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29825. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29826. uvs.push(u, v);
  29827. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29828. y = x * Math.sin(ang) + y * Math.cos(ang);
  29829. x = tmp;
  29830. // colors
  29831. if (faceColors) {
  29832. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29833. }
  29834. }
  29835. // indices from indexes
  29836. for (i = 0; i < fl - 2; i++) {
  29837. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29838. }
  29839. faceIdx += fl;
  29840. }
  29841. }
  29842. VertexData.ComputeNormals(positions, indices, normals);
  29843. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29844. var vertexData = new VertexData();
  29845. vertexData.positions = positions;
  29846. vertexData.indices = indices;
  29847. vertexData.normals = normals;
  29848. vertexData.uvs = uvs;
  29849. if (faceColors && flat) {
  29850. vertexData.colors = colors;
  29851. }
  29852. return vertexData;
  29853. };
  29854. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29855. /**
  29856. * Creates the VertexData of the Torus Knot.
  29857. */
  29858. VertexData.CreateTorusKnot = function (options) {
  29859. var indices = new Array();
  29860. var positions = new Array();
  29861. var normals = new Array();
  29862. var uvs = new Array();
  29863. var radius = options.radius || 2;
  29864. var tube = options.tube || 0.5;
  29865. var radialSegments = options.radialSegments || 32;
  29866. var tubularSegments = options.tubularSegments || 32;
  29867. var p = options.p || 2;
  29868. var q = options.q || 3;
  29869. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29870. // Helper
  29871. var getPos = function (angle) {
  29872. var cu = Math.cos(angle);
  29873. var su = Math.sin(angle);
  29874. var quOverP = q / p * angle;
  29875. var cs = Math.cos(quOverP);
  29876. var tx = radius * (2 + cs) * 0.5 * cu;
  29877. var ty = radius * (2 + cs) * su * 0.5;
  29878. var tz = radius * Math.sin(quOverP) * 0.5;
  29879. return new BABYLON.Vector3(tx, ty, tz);
  29880. };
  29881. // Vertices
  29882. var i;
  29883. var j;
  29884. for (i = 0; i <= radialSegments; i++) {
  29885. var modI = i % radialSegments;
  29886. var u = modI / radialSegments * 2 * p * Math.PI;
  29887. var p1 = getPos(u);
  29888. var p2 = getPos(u + 0.01);
  29889. var tang = p2.subtract(p1);
  29890. var n = p2.add(p1);
  29891. var bitan = BABYLON.Vector3.Cross(tang, n);
  29892. n = BABYLON.Vector3.Cross(bitan, tang);
  29893. bitan.normalize();
  29894. n.normalize();
  29895. for (j = 0; j < tubularSegments; j++) {
  29896. var modJ = j % tubularSegments;
  29897. var v = modJ / tubularSegments * 2 * Math.PI;
  29898. var cx = -tube * Math.cos(v);
  29899. var cy = tube * Math.sin(v);
  29900. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29901. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29902. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29903. uvs.push(i / radialSegments);
  29904. uvs.push(j / tubularSegments);
  29905. }
  29906. }
  29907. for (i = 0; i < radialSegments; i++) {
  29908. for (j = 0; j < tubularSegments; j++) {
  29909. var jNext = (j + 1) % tubularSegments;
  29910. var a = i * tubularSegments + j;
  29911. var b = (i + 1) * tubularSegments + j;
  29912. var c = (i + 1) * tubularSegments + jNext;
  29913. var d = i * tubularSegments + jNext;
  29914. indices.push(d);
  29915. indices.push(b);
  29916. indices.push(a);
  29917. indices.push(d);
  29918. indices.push(c);
  29919. indices.push(b);
  29920. }
  29921. }
  29922. // Normals
  29923. VertexData.ComputeNormals(positions, indices, normals);
  29924. // Sides
  29925. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29926. // Result
  29927. var vertexData = new VertexData();
  29928. vertexData.indices = indices;
  29929. vertexData.positions = positions;
  29930. vertexData.normals = normals;
  29931. vertexData.uvs = uvs;
  29932. return vertexData;
  29933. };
  29934. // Tools
  29935. /**
  29936. * @param {any} - positions (number[] or Float32Array)
  29937. * @param {any} - indices (number[] or Uint16Array)
  29938. * @param {any} - normals (number[] or Float32Array)
  29939. * options (optional) :
  29940. * facetPositions : optional array of facet positions (vector3)
  29941. * facetNormals : optional array of facet normals (vector3)
  29942. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29943. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29944. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29945. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29946. * bInfo : optional bounding info, required for facetPartitioning computation
  29947. */
  29948. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29949. // temporary scalar variables
  29950. var index = 0; // facet index
  29951. var p1p2x = 0.0; // p1p2 vector x coordinate
  29952. var p1p2y = 0.0; // p1p2 vector y coordinate
  29953. var p1p2z = 0.0; // p1p2 vector z coordinate
  29954. var p3p2x = 0.0; // p3p2 vector x coordinate
  29955. var p3p2y = 0.0; // p3p2 vector y coordinate
  29956. var p3p2z = 0.0; // p3p2 vector z coordinate
  29957. var faceNormalx = 0.0; // facet normal x coordinate
  29958. var faceNormaly = 0.0; // facet normal y coordinate
  29959. var faceNormalz = 0.0; // facet normal z coordinate
  29960. var length = 0.0; // facet normal length before normalization
  29961. var v1x = 0; // vector1 x index in the positions array
  29962. var v1y = 0; // vector1 y index in the positions array
  29963. var v1z = 0; // vector1 z index in the positions array
  29964. var v2x = 0; // vector2 x index in the positions array
  29965. var v2y = 0; // vector2 y index in the positions array
  29966. var v2z = 0; // vector2 z index in the positions array
  29967. var v3x = 0; // vector3 x index in the positions array
  29968. var v3y = 0; // vector3 y index in the positions array
  29969. var v3z = 0; // vector3 z index in the positions array
  29970. var computeFacetNormals = false;
  29971. var computeFacetPositions = false;
  29972. var computeFacetPartitioning = false;
  29973. var faceNormalSign = 1;
  29974. var ratio = 0;
  29975. if (options) {
  29976. computeFacetNormals = (options.facetNormals) ? true : false;
  29977. computeFacetPositions = (options.facetPositions) ? true : false;
  29978. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29979. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29980. ratio = options.ratio || 0;
  29981. }
  29982. // facetPartitioning reinit if needed
  29983. var xSubRatio = 0;
  29984. var ySubRatio = 0;
  29985. var zSubRatio = 0;
  29986. var subSq = 0;
  29987. if (computeFacetPartitioning && options && options.bbSize) {
  29988. var ox = 0; // X partitioning index for facet position
  29989. var oy = 0; // Y partinioning index for facet position
  29990. var oz = 0; // Z partinioning index for facet position
  29991. var b1x = 0; // X partitioning index for facet v1 vertex
  29992. var b1y = 0; // Y partitioning index for facet v1 vertex
  29993. var b1z = 0; // z partitioning index for facet v1 vertex
  29994. var b2x = 0; // X partitioning index for facet v2 vertex
  29995. var b2y = 0; // Y partitioning index for facet v2 vertex
  29996. var b2z = 0; // Z partitioning index for facet v2 vertex
  29997. var b3x = 0; // X partitioning index for facet v3 vertex
  29998. var b3y = 0; // Y partitioning index for facet v3 vertex
  29999. var b3z = 0; // Z partitioning index for facet v3 vertex
  30000. var block_idx_o = 0; // facet barycenter block index
  30001. var block_idx_v1 = 0; // v1 vertex block index
  30002. var block_idx_v2 = 0; // v2 vertex block index
  30003. var block_idx_v3 = 0; // v3 vertex block index
  30004. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30005. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30006. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30007. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30008. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30009. subSq = options.subDiv.max * options.subDiv.max;
  30010. options.facetPartitioning.length = 0;
  30011. }
  30012. // reset the normals
  30013. for (index = 0; index < positions.length; index++) {
  30014. normals[index] = 0.0;
  30015. }
  30016. // Loop : 1 indice triplet = 1 facet
  30017. var nbFaces = indices.length / 3;
  30018. for (index = 0; index < nbFaces; index++) {
  30019. // get the indexes of the coordinates of each vertex of the facet
  30020. v1x = indices[index * 3] * 3;
  30021. v1y = v1x + 1;
  30022. v1z = v1x + 2;
  30023. v2x = indices[index * 3 + 1] * 3;
  30024. v2y = v2x + 1;
  30025. v2z = v2x + 2;
  30026. v3x = indices[index * 3 + 2] * 3;
  30027. v3y = v3x + 1;
  30028. v3z = v3x + 2;
  30029. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30030. p1p2y = positions[v1y] - positions[v2y];
  30031. p1p2z = positions[v1z] - positions[v2z];
  30032. p3p2x = positions[v3x] - positions[v2x];
  30033. p3p2y = positions[v3y] - positions[v2y];
  30034. p3p2z = positions[v3z] - positions[v2z];
  30035. // compute the face normal with the cross product
  30036. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30037. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30038. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30039. // normalize this normal and store it in the array facetData
  30040. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30041. length = (length === 0) ? 1.0 : length;
  30042. faceNormalx /= length;
  30043. faceNormaly /= length;
  30044. faceNormalz /= length;
  30045. if (computeFacetNormals && options) {
  30046. options.facetNormals[index].x = faceNormalx;
  30047. options.facetNormals[index].y = faceNormaly;
  30048. options.facetNormals[index].z = faceNormalz;
  30049. }
  30050. if (computeFacetPositions && options) {
  30051. // compute and the facet barycenter coordinates in the array facetPositions
  30052. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30053. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30054. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30055. }
  30056. if (computeFacetPartitioning && options) {
  30057. // store the facet indexes in arrays in the main facetPartitioning array :
  30058. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30059. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30060. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30061. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30062. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30063. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30064. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30065. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30066. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30067. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30068. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30069. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30070. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30071. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30072. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30073. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30074. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30075. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30076. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30077. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30078. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30079. // push each facet index in each block containing the vertex
  30080. options.facetPartitioning[block_idx_v1].push(index);
  30081. if (block_idx_v2 != block_idx_v1) {
  30082. options.facetPartitioning[block_idx_v2].push(index);
  30083. }
  30084. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30085. options.facetPartitioning[block_idx_v3].push(index);
  30086. }
  30087. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30088. options.facetPartitioning[block_idx_o].push(index);
  30089. }
  30090. }
  30091. // compute the normals anyway
  30092. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30093. normals[v1y] += faceNormaly;
  30094. normals[v1z] += faceNormalz;
  30095. normals[v2x] += faceNormalx;
  30096. normals[v2y] += faceNormaly;
  30097. normals[v2z] += faceNormalz;
  30098. normals[v3x] += faceNormalx;
  30099. normals[v3y] += faceNormaly;
  30100. normals[v3z] += faceNormalz;
  30101. }
  30102. // last normalization of each normal
  30103. for (index = 0; index < normals.length / 3; index++) {
  30104. faceNormalx = normals[index * 3];
  30105. faceNormaly = normals[index * 3 + 1];
  30106. faceNormalz = normals[index * 3 + 2];
  30107. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30108. length = (length === 0) ? 1.0 : length;
  30109. faceNormalx /= length;
  30110. faceNormaly /= length;
  30111. faceNormalz /= length;
  30112. normals[index * 3] = faceNormalx;
  30113. normals[index * 3 + 1] = faceNormaly;
  30114. normals[index * 3 + 2] = faceNormalz;
  30115. }
  30116. };
  30117. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30118. var li = indices.length;
  30119. var ln = normals.length;
  30120. var i;
  30121. var n;
  30122. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30123. switch (sideOrientation) {
  30124. case BABYLON.Mesh.FRONTSIDE:
  30125. // nothing changed
  30126. break;
  30127. case BABYLON.Mesh.BACKSIDE:
  30128. var tmp;
  30129. // indices
  30130. for (i = 0; i < li; i += 3) {
  30131. tmp = indices[i];
  30132. indices[i] = indices[i + 2];
  30133. indices[i + 2] = tmp;
  30134. }
  30135. // normals
  30136. for (n = 0; n < ln; n++) {
  30137. normals[n] = -normals[n];
  30138. }
  30139. break;
  30140. case BABYLON.Mesh.DOUBLESIDE:
  30141. // positions
  30142. var lp = positions.length;
  30143. var l = lp / 3;
  30144. for (var p = 0; p < lp; p++) {
  30145. positions[lp + p] = positions[p];
  30146. }
  30147. // indices
  30148. for (i = 0; i < li; i += 3) {
  30149. indices[i + li] = indices[i + 2] + l;
  30150. indices[i + 1 + li] = indices[i + 1] + l;
  30151. indices[i + 2 + li] = indices[i] + l;
  30152. }
  30153. // normals
  30154. for (n = 0; n < ln; n++) {
  30155. normals[ln + n] = -normals[n];
  30156. }
  30157. // uvs
  30158. var lu = uvs.length;
  30159. var u = 0;
  30160. for (u = 0; u < lu; u++) {
  30161. uvs[u + lu] = uvs[u];
  30162. }
  30163. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30164. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30165. u = 0;
  30166. for (i = 0; i < lu / 2; i++) {
  30167. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30168. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30169. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30170. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30171. u += 2;
  30172. }
  30173. break;
  30174. }
  30175. };
  30176. /**
  30177. * Creates a new VertexData from the imported parameters.
  30178. */
  30179. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30180. var vertexData = new VertexData();
  30181. // positions
  30182. var positions = parsedVertexData.positions;
  30183. if (positions) {
  30184. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30185. }
  30186. // normals
  30187. var normals = parsedVertexData.normals;
  30188. if (normals) {
  30189. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30190. }
  30191. // tangents
  30192. var tangents = parsedVertexData.tangents;
  30193. if (tangents) {
  30194. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30195. }
  30196. // uvs
  30197. var uvs = parsedVertexData.uvs;
  30198. if (uvs) {
  30199. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30200. }
  30201. // uv2s
  30202. var uv2s = parsedVertexData.uv2s;
  30203. if (uv2s) {
  30204. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30205. }
  30206. // uv3s
  30207. var uv3s = parsedVertexData.uv3s;
  30208. if (uv3s) {
  30209. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30210. }
  30211. // uv4s
  30212. var uv4s = parsedVertexData.uv4s;
  30213. if (uv4s) {
  30214. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30215. }
  30216. // uv5s
  30217. var uv5s = parsedVertexData.uv5s;
  30218. if (uv5s) {
  30219. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30220. }
  30221. // uv6s
  30222. var uv6s = parsedVertexData.uv6s;
  30223. if (uv6s) {
  30224. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30225. }
  30226. // colors
  30227. var colors = parsedVertexData.colors;
  30228. if (colors) {
  30229. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30230. }
  30231. // matricesIndices
  30232. var matricesIndices = parsedVertexData.matricesIndices;
  30233. if (matricesIndices) {
  30234. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30235. }
  30236. // matricesWeights
  30237. var matricesWeights = parsedVertexData.matricesWeights;
  30238. if (matricesWeights) {
  30239. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30240. }
  30241. // indices
  30242. var indices = parsedVertexData.indices;
  30243. if (indices) {
  30244. vertexData.indices = indices;
  30245. }
  30246. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30247. };
  30248. return VertexData;
  30249. }());
  30250. BABYLON.VertexData = VertexData;
  30251. })(BABYLON || (BABYLON = {}));
  30252. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30253. var BABYLON;
  30254. (function (BABYLON) {
  30255. var Geometry = /** @class */ (function () {
  30256. function Geometry(id, scene, vertexData, updatable, mesh) {
  30257. if (updatable === void 0) { updatable = false; }
  30258. if (mesh === void 0) { mesh = null; }
  30259. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30260. this._totalVertices = 0;
  30261. this._isDisposed = false;
  30262. this._indexBufferIsUpdatable = false;
  30263. this.id = id;
  30264. this._engine = scene.getEngine();
  30265. this._meshes = [];
  30266. this._scene = scene;
  30267. //Init vertex buffer cache
  30268. this._vertexBuffers = {};
  30269. this._indices = [];
  30270. this._updatable = updatable;
  30271. // vertexData
  30272. if (vertexData) {
  30273. this.setAllVerticesData(vertexData, updatable);
  30274. }
  30275. else {
  30276. this._totalVertices = 0;
  30277. this._indices = [];
  30278. }
  30279. if (this._engine.getCaps().vertexArrayObject) {
  30280. this._vertexArrayObjects = {};
  30281. }
  30282. // applyToMesh
  30283. if (mesh) {
  30284. if (mesh.getClassName() === "LinesMesh") {
  30285. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30286. this.updateExtend();
  30287. }
  30288. this.applyToMesh(mesh);
  30289. mesh.computeWorldMatrix(true);
  30290. }
  30291. }
  30292. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30293. /**
  30294. * 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
  30295. * @returns The Bias Vector
  30296. */
  30297. get: function () {
  30298. return this._boundingBias;
  30299. },
  30300. set: function (value) {
  30301. if (this._boundingBias && this._boundingBias.equals(value)) {
  30302. return;
  30303. }
  30304. this._boundingBias = value.clone();
  30305. this.updateBoundingInfo(true, null);
  30306. },
  30307. enumerable: true,
  30308. configurable: true
  30309. });
  30310. Geometry.CreateGeometryForMesh = function (mesh) {
  30311. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30312. geometry.applyToMesh(mesh);
  30313. return geometry;
  30314. };
  30315. Object.defineProperty(Geometry.prototype, "extend", {
  30316. get: function () {
  30317. return this._extend;
  30318. },
  30319. enumerable: true,
  30320. configurable: true
  30321. });
  30322. Geometry.prototype.getScene = function () {
  30323. return this._scene;
  30324. };
  30325. Geometry.prototype.getEngine = function () {
  30326. return this._engine;
  30327. };
  30328. Geometry.prototype.isReady = function () {
  30329. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30330. };
  30331. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30332. get: function () {
  30333. for (var index = 0; index < this._meshes.length; index++) {
  30334. if (!this._meshes[index].doNotSerialize) {
  30335. return false;
  30336. }
  30337. }
  30338. return true;
  30339. },
  30340. enumerable: true,
  30341. configurable: true
  30342. });
  30343. Geometry.prototype._rebuild = function () {
  30344. if (this._vertexArrayObjects) {
  30345. this._vertexArrayObjects = {};
  30346. }
  30347. // Index buffer
  30348. if (this._meshes.length !== 0 && this._indices) {
  30349. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30350. }
  30351. // Vertex buffers
  30352. for (var key in this._vertexBuffers) {
  30353. var vertexBuffer = this._vertexBuffers[key];
  30354. vertexBuffer._rebuild();
  30355. }
  30356. };
  30357. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30358. vertexData.applyToGeometry(this, updatable);
  30359. this.notifyUpdate();
  30360. };
  30361. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30362. if (updatable === void 0) { updatable = false; }
  30363. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30364. this.setVerticesBuffer(buffer);
  30365. };
  30366. Geometry.prototype.removeVerticesData = function (kind) {
  30367. if (this._vertexBuffers[kind]) {
  30368. this._vertexBuffers[kind].dispose();
  30369. delete this._vertexBuffers[kind];
  30370. }
  30371. };
  30372. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30373. var kind = buffer.getKind();
  30374. if (this._vertexBuffers[kind]) {
  30375. this._vertexBuffers[kind].dispose();
  30376. }
  30377. this._vertexBuffers[kind] = buffer;
  30378. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30379. var data = buffer.getData();
  30380. var stride = buffer.getStrideSize();
  30381. this._totalVertices = data.length / stride;
  30382. this.updateExtend(data, stride);
  30383. this._resetPointsArrayCache();
  30384. var meshes = this._meshes;
  30385. var numOfMeshes = meshes.length;
  30386. for (var index = 0; index < numOfMeshes; index++) {
  30387. var mesh = meshes[index];
  30388. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30389. mesh._createGlobalSubMesh(false);
  30390. mesh.computeWorldMatrix(true);
  30391. }
  30392. }
  30393. this.notifyUpdate(kind);
  30394. if (this._vertexArrayObjects) {
  30395. this._disposeVertexArrayObjects();
  30396. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30397. }
  30398. };
  30399. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30400. var vertexBuffer = this.getVertexBuffer(kind);
  30401. if (!vertexBuffer) {
  30402. return;
  30403. }
  30404. vertexBuffer.updateDirectly(data, offset);
  30405. this.notifyUpdate(kind);
  30406. };
  30407. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30408. if (updateExtends === void 0) { updateExtends = false; }
  30409. var vertexBuffer = this.getVertexBuffer(kind);
  30410. if (!vertexBuffer) {
  30411. return;
  30412. }
  30413. vertexBuffer.update(data);
  30414. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30415. var stride = vertexBuffer.getStrideSize();
  30416. this._totalVertices = data.length / stride;
  30417. this.updateBoundingInfo(updateExtends, data);
  30418. }
  30419. this.notifyUpdate(kind);
  30420. };
  30421. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30422. if (updateExtends) {
  30423. this.updateExtend(data);
  30424. }
  30425. var meshes = this._meshes;
  30426. var numOfMeshes = meshes.length;
  30427. this._resetPointsArrayCache();
  30428. for (var index = 0; index < numOfMeshes; index++) {
  30429. var mesh = meshes[index];
  30430. if (updateExtends) {
  30431. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30432. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30433. var subMesh = mesh.subMeshes[subIndex];
  30434. subMesh.refreshBoundingInfo();
  30435. }
  30436. }
  30437. }
  30438. };
  30439. Geometry.prototype._bind = function (effect, indexToBind) {
  30440. if (!effect) {
  30441. return;
  30442. }
  30443. if (indexToBind === undefined) {
  30444. indexToBind = this._indexBuffer;
  30445. }
  30446. var vbs = this.getVertexBuffers();
  30447. if (!vbs) {
  30448. return;
  30449. }
  30450. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30451. this._engine.bindBuffers(vbs, indexToBind, effect);
  30452. return;
  30453. }
  30454. // Using VAO
  30455. if (!this._vertexArrayObjects[effect.key]) {
  30456. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30457. }
  30458. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30459. };
  30460. Geometry.prototype.getTotalVertices = function () {
  30461. if (!this.isReady()) {
  30462. return 0;
  30463. }
  30464. return this._totalVertices;
  30465. };
  30466. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30467. var vertexBuffer = this.getVertexBuffer(kind);
  30468. if (!vertexBuffer) {
  30469. return null;
  30470. }
  30471. var orig = vertexBuffer.getData();
  30472. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30473. return orig;
  30474. }
  30475. else {
  30476. var len = orig.length;
  30477. var copy = [];
  30478. for (var i = 0; i < len; i++) {
  30479. copy.push(orig[i]);
  30480. }
  30481. return copy;
  30482. }
  30483. };
  30484. /**
  30485. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30486. * Possible `kind` values :
  30487. * - BABYLON.VertexBuffer.PositionKind
  30488. * - BABYLON.VertexBuffer.UVKind
  30489. * - BABYLON.VertexBuffer.UV2Kind
  30490. * - BABYLON.VertexBuffer.UV3Kind
  30491. * - BABYLON.VertexBuffer.UV4Kind
  30492. * - BABYLON.VertexBuffer.UV5Kind
  30493. * - BABYLON.VertexBuffer.UV6Kind
  30494. * - BABYLON.VertexBuffer.ColorKind
  30495. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30496. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30497. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30498. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30499. */
  30500. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30501. var vb = this._vertexBuffers[kind];
  30502. if (!vb) {
  30503. return false;
  30504. }
  30505. return vb.isUpdatable();
  30506. };
  30507. Geometry.prototype.getVertexBuffer = function (kind) {
  30508. if (!this.isReady()) {
  30509. return null;
  30510. }
  30511. return this._vertexBuffers[kind];
  30512. };
  30513. Geometry.prototype.getVertexBuffers = function () {
  30514. if (!this.isReady()) {
  30515. return null;
  30516. }
  30517. return this._vertexBuffers;
  30518. };
  30519. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30520. if (!this._vertexBuffers) {
  30521. if (this._delayInfo) {
  30522. return this._delayInfo.indexOf(kind) !== -1;
  30523. }
  30524. return false;
  30525. }
  30526. return this._vertexBuffers[kind] !== undefined;
  30527. };
  30528. Geometry.prototype.getVerticesDataKinds = function () {
  30529. var result = [];
  30530. var kind;
  30531. if (!this._vertexBuffers && this._delayInfo) {
  30532. for (kind in this._delayInfo) {
  30533. result.push(kind);
  30534. }
  30535. }
  30536. else {
  30537. for (kind in this._vertexBuffers) {
  30538. result.push(kind);
  30539. }
  30540. }
  30541. return result;
  30542. };
  30543. Geometry.prototype.updateIndices = function (indices, offset) {
  30544. if (!this._indexBuffer) {
  30545. return;
  30546. }
  30547. if (!this._indexBufferIsUpdatable) {
  30548. this.setIndices(indices, null, true);
  30549. }
  30550. else {
  30551. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30552. }
  30553. };
  30554. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30555. if (totalVertices === void 0) { totalVertices = null; }
  30556. if (updatable === void 0) { updatable = false; }
  30557. if (this._indexBuffer) {
  30558. this._engine._releaseBuffer(this._indexBuffer);
  30559. }
  30560. this._disposeVertexArrayObjects();
  30561. this._indices = indices;
  30562. this._indexBufferIsUpdatable = updatable;
  30563. if (this._meshes.length !== 0 && this._indices) {
  30564. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30565. }
  30566. if (totalVertices != undefined) {
  30567. this._totalVertices = totalVertices;
  30568. }
  30569. var meshes = this._meshes;
  30570. var numOfMeshes = meshes.length;
  30571. for (var index = 0; index < numOfMeshes; index++) {
  30572. meshes[index]._createGlobalSubMesh(true);
  30573. }
  30574. this.notifyUpdate();
  30575. };
  30576. Geometry.prototype.getTotalIndices = function () {
  30577. if (!this.isReady()) {
  30578. return 0;
  30579. }
  30580. return this._indices.length;
  30581. };
  30582. Geometry.prototype.getIndices = function (copyWhenShared) {
  30583. if (!this.isReady()) {
  30584. return null;
  30585. }
  30586. var orig = this._indices;
  30587. if (!copyWhenShared || this._meshes.length === 1) {
  30588. return orig;
  30589. }
  30590. else {
  30591. var len = orig.length;
  30592. var copy = [];
  30593. for (var i = 0; i < len; i++) {
  30594. copy.push(orig[i]);
  30595. }
  30596. return copy;
  30597. }
  30598. };
  30599. Geometry.prototype.getIndexBuffer = function () {
  30600. if (!this.isReady()) {
  30601. return null;
  30602. }
  30603. return this._indexBuffer;
  30604. };
  30605. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30606. if (effect === void 0) { effect = null; }
  30607. if (!effect || !this._vertexArrayObjects) {
  30608. return;
  30609. }
  30610. if (this._vertexArrayObjects[effect.key]) {
  30611. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30612. delete this._vertexArrayObjects[effect.key];
  30613. }
  30614. };
  30615. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30616. var meshes = this._meshes;
  30617. var index = meshes.indexOf(mesh);
  30618. if (index === -1) {
  30619. return;
  30620. }
  30621. meshes.splice(index, 1);
  30622. mesh._geometry = null;
  30623. if (meshes.length === 0 && shouldDispose) {
  30624. this.dispose();
  30625. }
  30626. };
  30627. Geometry.prototype.applyToMesh = function (mesh) {
  30628. if (mesh._geometry === this) {
  30629. return;
  30630. }
  30631. var previousGeometry = mesh._geometry;
  30632. if (previousGeometry) {
  30633. previousGeometry.releaseForMesh(mesh);
  30634. }
  30635. var meshes = this._meshes;
  30636. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30637. mesh._geometry = this;
  30638. this._scene.pushGeometry(this);
  30639. meshes.push(mesh);
  30640. if (this.isReady()) {
  30641. this._applyToMesh(mesh);
  30642. }
  30643. else {
  30644. mesh._boundingInfo = this._boundingInfo;
  30645. }
  30646. };
  30647. Geometry.prototype.updateExtend = function (data, stride) {
  30648. if (data === void 0) { data = null; }
  30649. if (!data) {
  30650. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30651. }
  30652. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30653. };
  30654. Geometry.prototype._applyToMesh = function (mesh) {
  30655. var numOfMeshes = this._meshes.length;
  30656. // vertexBuffers
  30657. for (var kind in this._vertexBuffers) {
  30658. if (numOfMeshes === 1) {
  30659. this._vertexBuffers[kind].create();
  30660. }
  30661. var buffer = this._vertexBuffers[kind].getBuffer();
  30662. if (buffer)
  30663. buffer.references = numOfMeshes;
  30664. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30665. if (!this._extend) {
  30666. this.updateExtend(this._vertexBuffers[kind].getData());
  30667. }
  30668. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30669. mesh._createGlobalSubMesh(false);
  30670. //bounding info was just created again, world matrix should be applied again.
  30671. mesh._updateBoundingInfo();
  30672. }
  30673. }
  30674. // indexBuffer
  30675. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30676. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30677. }
  30678. if (this._indexBuffer) {
  30679. this._indexBuffer.references = numOfMeshes;
  30680. }
  30681. };
  30682. Geometry.prototype.notifyUpdate = function (kind) {
  30683. if (this.onGeometryUpdated) {
  30684. this.onGeometryUpdated(this, kind);
  30685. }
  30686. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30687. var mesh = _a[_i];
  30688. mesh._markSubMeshesAsAttributesDirty();
  30689. }
  30690. };
  30691. Geometry.prototype.load = function (scene, onLoaded) {
  30692. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30693. return;
  30694. }
  30695. if (this.isReady()) {
  30696. if (onLoaded) {
  30697. onLoaded();
  30698. }
  30699. return;
  30700. }
  30701. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30702. this._queueLoad(scene, onLoaded);
  30703. };
  30704. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30705. var _this = this;
  30706. if (!this.delayLoadingFile) {
  30707. return;
  30708. }
  30709. scene._addPendingData(this);
  30710. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30711. if (!_this._delayLoadingFunction) {
  30712. return;
  30713. }
  30714. _this._delayLoadingFunction(JSON.parse(data), _this);
  30715. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30716. _this._delayInfo = [];
  30717. scene._removePendingData(_this);
  30718. var meshes = _this._meshes;
  30719. var numOfMeshes = meshes.length;
  30720. for (var index = 0; index < numOfMeshes; index++) {
  30721. _this._applyToMesh(meshes[index]);
  30722. }
  30723. if (onLoaded) {
  30724. onLoaded();
  30725. }
  30726. }, function () { }, scene.database);
  30727. };
  30728. /**
  30729. * Invert the geometry to move from a right handed system to a left handed one.
  30730. */
  30731. Geometry.prototype.toLeftHanded = function () {
  30732. // Flip faces
  30733. var tIndices = this.getIndices(false);
  30734. if (tIndices != null && tIndices.length > 0) {
  30735. for (var i = 0; i < tIndices.length; i += 3) {
  30736. var tTemp = tIndices[i + 0];
  30737. tIndices[i + 0] = tIndices[i + 2];
  30738. tIndices[i + 2] = tTemp;
  30739. }
  30740. this.setIndices(tIndices);
  30741. }
  30742. // Negate position.z
  30743. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30744. if (tPositions != null && tPositions.length > 0) {
  30745. for (var i = 0; i < tPositions.length; i += 3) {
  30746. tPositions[i + 2] = -tPositions[i + 2];
  30747. }
  30748. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30749. }
  30750. // Negate normal.z
  30751. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30752. if (tNormals != null && tNormals.length > 0) {
  30753. for (var i = 0; i < tNormals.length; i += 3) {
  30754. tNormals[i + 2] = -tNormals[i + 2];
  30755. }
  30756. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30757. }
  30758. };
  30759. // Cache
  30760. Geometry.prototype._resetPointsArrayCache = function () {
  30761. this._positions = null;
  30762. };
  30763. Geometry.prototype._generatePointsArray = function () {
  30764. if (this._positions)
  30765. return true;
  30766. this._positions = [];
  30767. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30768. if (!data) {
  30769. return false;
  30770. }
  30771. for (var index = 0; index < data.length; index += 3) {
  30772. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30773. }
  30774. return true;
  30775. };
  30776. Geometry.prototype.isDisposed = function () {
  30777. return this._isDisposed;
  30778. };
  30779. Geometry.prototype._disposeVertexArrayObjects = function () {
  30780. if (this._vertexArrayObjects) {
  30781. for (var kind in this._vertexArrayObjects) {
  30782. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30783. }
  30784. this._vertexArrayObjects = {};
  30785. }
  30786. };
  30787. Geometry.prototype.dispose = function () {
  30788. var meshes = this._meshes;
  30789. var numOfMeshes = meshes.length;
  30790. var index;
  30791. for (index = 0; index < numOfMeshes; index++) {
  30792. this.releaseForMesh(meshes[index]);
  30793. }
  30794. this._meshes = [];
  30795. this._disposeVertexArrayObjects();
  30796. for (var kind in this._vertexBuffers) {
  30797. this._vertexBuffers[kind].dispose();
  30798. }
  30799. this._vertexBuffers = {};
  30800. this._totalVertices = 0;
  30801. if (this._indexBuffer) {
  30802. this._engine._releaseBuffer(this._indexBuffer);
  30803. }
  30804. this._indexBuffer = null;
  30805. this._indices = [];
  30806. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30807. this.delayLoadingFile = null;
  30808. this._delayLoadingFunction = null;
  30809. this._delayInfo = [];
  30810. this._boundingInfo = null;
  30811. this._scene.removeGeometry(this);
  30812. this._isDisposed = true;
  30813. };
  30814. Geometry.prototype.copy = function (id) {
  30815. var vertexData = new BABYLON.VertexData();
  30816. vertexData.indices = [];
  30817. var indices = this.getIndices();
  30818. if (indices) {
  30819. for (var index = 0; index < indices.length; index++) {
  30820. vertexData.indices.push(indices[index]);
  30821. }
  30822. }
  30823. var updatable = false;
  30824. var stopChecking = false;
  30825. var kind;
  30826. for (kind in this._vertexBuffers) {
  30827. // using slice() to make a copy of the array and not just reference it
  30828. var data = this.getVerticesData(kind);
  30829. if (data instanceof Float32Array) {
  30830. vertexData.set(new Float32Array(data), kind);
  30831. }
  30832. else {
  30833. vertexData.set(data.slice(0), kind);
  30834. }
  30835. if (!stopChecking) {
  30836. var vb = this.getVertexBuffer(kind);
  30837. if (vb) {
  30838. updatable = vb.isUpdatable();
  30839. stopChecking = !updatable;
  30840. }
  30841. }
  30842. }
  30843. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30844. geometry.delayLoadState = this.delayLoadState;
  30845. geometry.delayLoadingFile = this.delayLoadingFile;
  30846. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30847. for (kind in this._delayInfo) {
  30848. geometry._delayInfo = geometry._delayInfo || [];
  30849. geometry._delayInfo.push(kind);
  30850. }
  30851. // Bounding info
  30852. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30853. return geometry;
  30854. };
  30855. Geometry.prototype.serialize = function () {
  30856. var serializationObject = {};
  30857. serializationObject.id = this.id;
  30858. serializationObject.updatable = this._updatable;
  30859. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30860. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30861. }
  30862. return serializationObject;
  30863. };
  30864. Geometry.prototype.toNumberArray = function (origin) {
  30865. if (Array.isArray(origin)) {
  30866. return origin;
  30867. }
  30868. else {
  30869. return Array.prototype.slice.call(origin);
  30870. }
  30871. };
  30872. Geometry.prototype.serializeVerticeData = function () {
  30873. var serializationObject = this.serialize();
  30874. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30875. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30876. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30877. serializationObject.positions._updatable = true;
  30878. }
  30879. }
  30880. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30881. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30882. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30883. serializationObject.normals._updatable = true;
  30884. }
  30885. }
  30886. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30887. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30888. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30889. serializationObject.uvs._updatable = true;
  30890. }
  30891. }
  30892. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30893. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30894. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30895. serializationObject.uv2s._updatable = true;
  30896. }
  30897. }
  30898. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30899. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30900. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30901. serializationObject.uv3s._updatable = true;
  30902. }
  30903. }
  30904. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30905. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30906. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30907. serializationObject.uv4s._updatable = true;
  30908. }
  30909. }
  30910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30911. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30912. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30913. serializationObject.uv5s._updatable = true;
  30914. }
  30915. }
  30916. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30917. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30918. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30919. serializationObject.uv6s._updatable = true;
  30920. }
  30921. }
  30922. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30923. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30924. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30925. serializationObject.colors._updatable = true;
  30926. }
  30927. }
  30928. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30929. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30930. serializationObject.matricesIndices._isExpanded = true;
  30931. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30932. serializationObject.matricesIndices._updatable = true;
  30933. }
  30934. }
  30935. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30936. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30937. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30938. serializationObject.matricesWeights._updatable = true;
  30939. }
  30940. }
  30941. serializationObject.indices = this.toNumberArray(this.getIndices());
  30942. return serializationObject;
  30943. };
  30944. // Statics
  30945. Geometry.ExtractFromMesh = function (mesh, id) {
  30946. var geometry = mesh._geometry;
  30947. if (!geometry) {
  30948. return null;
  30949. }
  30950. return geometry.copy(id);
  30951. };
  30952. /**
  30953. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30954. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30955. * Be aware Math.random() could cause collisions, but:
  30956. * "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"
  30957. */
  30958. Geometry.RandomId = function () {
  30959. return BABYLON.Tools.RandomId();
  30960. };
  30961. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30962. var scene = mesh.getScene();
  30963. // Geometry
  30964. var geometryId = parsedGeometry.geometryId;
  30965. if (geometryId) {
  30966. var geometry = scene.getGeometryByID(geometryId);
  30967. if (geometry) {
  30968. geometry.applyToMesh(mesh);
  30969. }
  30970. }
  30971. else if (parsedGeometry instanceof ArrayBuffer) {
  30972. var binaryInfo = mesh._binaryInfo;
  30973. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30974. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30975. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30976. }
  30977. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30978. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30979. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30980. }
  30981. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30982. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30983. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30984. }
  30985. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30986. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30987. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30988. }
  30989. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30990. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30991. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30992. }
  30993. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30994. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30995. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30996. }
  30997. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30998. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30999. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31000. }
  31001. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31002. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31003. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31004. }
  31005. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31006. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31007. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31008. }
  31009. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31010. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31011. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31012. }
  31013. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31014. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31015. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31016. }
  31017. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31018. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31019. mesh.setIndices(indicesData, null);
  31020. }
  31021. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31022. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31023. mesh.subMeshes = [];
  31024. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31025. var materialIndex = subMeshesData[(i * 5) + 0];
  31026. var verticesStart = subMeshesData[(i * 5) + 1];
  31027. var verticesCount = subMeshesData[(i * 5) + 2];
  31028. var indexStart = subMeshesData[(i * 5) + 3];
  31029. var indexCount = subMeshesData[(i * 5) + 4];
  31030. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31031. }
  31032. }
  31033. }
  31034. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31035. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31036. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31037. if (parsedGeometry.uvs) {
  31038. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31039. }
  31040. if (parsedGeometry.uvs2) {
  31041. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31042. }
  31043. if (parsedGeometry.uvs3) {
  31044. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31045. }
  31046. if (parsedGeometry.uvs4) {
  31047. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31048. }
  31049. if (parsedGeometry.uvs5) {
  31050. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31051. }
  31052. if (parsedGeometry.uvs6) {
  31053. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31054. }
  31055. if (parsedGeometry.colors) {
  31056. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31057. }
  31058. if (parsedGeometry.matricesIndices) {
  31059. if (!parsedGeometry.matricesIndices._isExpanded) {
  31060. var floatIndices = [];
  31061. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31062. var matricesIndex = parsedGeometry.matricesIndices[i];
  31063. floatIndices.push(matricesIndex & 0x000000FF);
  31064. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31065. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31066. floatIndices.push(matricesIndex >> 24);
  31067. }
  31068. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31069. }
  31070. else {
  31071. delete parsedGeometry.matricesIndices._isExpanded;
  31072. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31073. }
  31074. }
  31075. if (parsedGeometry.matricesIndicesExtra) {
  31076. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31077. var floatIndices = [];
  31078. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31079. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31080. floatIndices.push(matricesIndex & 0x000000FF);
  31081. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31082. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31083. floatIndices.push(matricesIndex >> 24);
  31084. }
  31085. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31086. }
  31087. else {
  31088. delete parsedGeometry.matricesIndices._isExpanded;
  31089. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31090. }
  31091. }
  31092. if (parsedGeometry.matricesWeights) {
  31093. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31094. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31095. }
  31096. if (parsedGeometry.matricesWeightsExtra) {
  31097. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31098. }
  31099. mesh.setIndices(parsedGeometry.indices, null);
  31100. }
  31101. // SubMeshes
  31102. if (parsedGeometry.subMeshes) {
  31103. mesh.subMeshes = [];
  31104. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31105. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31106. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31107. }
  31108. }
  31109. // Flat shading
  31110. if (mesh._shouldGenerateFlatShading) {
  31111. mesh.convertToFlatShadedMesh();
  31112. delete mesh._shouldGenerateFlatShading;
  31113. }
  31114. // Update
  31115. mesh.computeWorldMatrix(true);
  31116. // Octree
  31117. if (scene['_selectionOctree']) {
  31118. scene['_selectionOctree'].addMesh(mesh);
  31119. }
  31120. };
  31121. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31122. var epsilon = 1e-3;
  31123. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31124. return;
  31125. }
  31126. var noInfluenceBoneIndex = 0.0;
  31127. if (parsedGeometry.skeletonId > -1) {
  31128. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31129. if (!skeleton) {
  31130. return;
  31131. }
  31132. noInfluenceBoneIndex = skeleton.bones.length;
  31133. }
  31134. else {
  31135. return;
  31136. }
  31137. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31138. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31139. var matricesWeights = parsedGeometry.matricesWeights;
  31140. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31141. var influencers = parsedGeometry.numBoneInfluencer;
  31142. var size = matricesWeights.length;
  31143. for (var i = 0; i < size; i += 4) {
  31144. var weight = 0.0;
  31145. var firstZeroWeight = -1;
  31146. for (var j = 0; j < 4; j++) {
  31147. var w = matricesWeights[i + j];
  31148. weight += w;
  31149. if (w < epsilon && firstZeroWeight < 0) {
  31150. firstZeroWeight = j;
  31151. }
  31152. }
  31153. if (matricesWeightsExtra) {
  31154. for (var j = 0; j < 4; j++) {
  31155. var w = matricesWeightsExtra[i + j];
  31156. weight += w;
  31157. if (w < epsilon && firstZeroWeight < 0) {
  31158. firstZeroWeight = j + 4;
  31159. }
  31160. }
  31161. }
  31162. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31163. firstZeroWeight = influencers - 1;
  31164. }
  31165. if (weight > epsilon) {
  31166. var mweight = 1.0 / weight;
  31167. for (var j = 0; j < 4; j++) {
  31168. matricesWeights[i + j] *= mweight;
  31169. }
  31170. if (matricesWeightsExtra) {
  31171. for (var j = 0; j < 4; j++) {
  31172. matricesWeightsExtra[i + j] *= mweight;
  31173. }
  31174. }
  31175. }
  31176. else {
  31177. if (firstZeroWeight >= 4) {
  31178. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31179. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31180. }
  31181. else {
  31182. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31183. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31184. }
  31185. }
  31186. }
  31187. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31188. if (parsedGeometry.matricesWeightsExtra) {
  31189. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31190. }
  31191. };
  31192. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31193. if (scene.getGeometryByID(parsedVertexData.id)) {
  31194. return null; // null since geometry could be something else than a box...
  31195. }
  31196. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31197. if (BABYLON.Tags) {
  31198. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31199. }
  31200. if (parsedVertexData.delayLoadingFile) {
  31201. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31202. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31203. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31204. geometry._delayInfo = [];
  31205. if (parsedVertexData.hasUVs) {
  31206. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31207. }
  31208. if (parsedVertexData.hasUVs2) {
  31209. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31210. }
  31211. if (parsedVertexData.hasUVs3) {
  31212. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31213. }
  31214. if (parsedVertexData.hasUVs4) {
  31215. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31216. }
  31217. if (parsedVertexData.hasUVs5) {
  31218. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31219. }
  31220. if (parsedVertexData.hasUVs6) {
  31221. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31222. }
  31223. if (parsedVertexData.hasColors) {
  31224. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31225. }
  31226. if (parsedVertexData.hasMatricesIndices) {
  31227. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31228. }
  31229. if (parsedVertexData.hasMatricesWeights) {
  31230. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31231. }
  31232. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31233. }
  31234. else {
  31235. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31236. }
  31237. scene.pushGeometry(geometry, true);
  31238. return geometry;
  31239. };
  31240. return Geometry;
  31241. }());
  31242. BABYLON.Geometry = Geometry;
  31243. /////// Primitives //////////////////////////////////////////////
  31244. (function (Geometry) {
  31245. var Primitives;
  31246. (function (Primitives) {
  31247. /// Abstract class
  31248. var _Primitive = /** @class */ (function (_super) {
  31249. __extends(_Primitive, _super);
  31250. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31251. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31252. if (mesh === void 0) { mesh = null; }
  31253. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31254. _this._canBeRegenerated = _canBeRegenerated;
  31255. _this._beingRegenerated = true;
  31256. _this.regenerate();
  31257. _this._beingRegenerated = false;
  31258. return _this;
  31259. }
  31260. _Primitive.prototype.canBeRegenerated = function () {
  31261. return this._canBeRegenerated;
  31262. };
  31263. _Primitive.prototype.regenerate = function () {
  31264. if (!this._canBeRegenerated) {
  31265. return;
  31266. }
  31267. this._beingRegenerated = true;
  31268. this.setAllVerticesData(this._regenerateVertexData(), false);
  31269. this._beingRegenerated = false;
  31270. };
  31271. _Primitive.prototype.asNewGeometry = function (id) {
  31272. return _super.prototype.copy.call(this, id);
  31273. };
  31274. // overrides
  31275. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31276. if (!this._beingRegenerated) {
  31277. return;
  31278. }
  31279. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31280. };
  31281. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31282. if (!this._beingRegenerated) {
  31283. return;
  31284. }
  31285. _super.prototype.setVerticesData.call(this, kind, data, false);
  31286. };
  31287. // to override
  31288. // protected
  31289. _Primitive.prototype._regenerateVertexData = function () {
  31290. throw new Error("Abstract method");
  31291. };
  31292. _Primitive.prototype.copy = function (id) {
  31293. throw new Error("Must be overriden in sub-classes.");
  31294. };
  31295. _Primitive.prototype.serialize = function () {
  31296. var serializationObject = _super.prototype.serialize.call(this);
  31297. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31298. return serializationObject;
  31299. };
  31300. return _Primitive;
  31301. }(Geometry));
  31302. Primitives._Primitive = _Primitive;
  31303. var Ribbon = /** @class */ (function (_super) {
  31304. __extends(Ribbon, _super);
  31305. // Members
  31306. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31307. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31308. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31309. _this.pathArray = pathArray;
  31310. _this.closeArray = closeArray;
  31311. _this.closePath = closePath;
  31312. _this.offset = offset;
  31313. _this.side = side;
  31314. return _this;
  31315. }
  31316. Ribbon.prototype._regenerateVertexData = function () {
  31317. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31318. };
  31319. Ribbon.prototype.copy = function (id) {
  31320. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31321. };
  31322. return Ribbon;
  31323. }(_Primitive));
  31324. Primitives.Ribbon = Ribbon;
  31325. var Box = /** @class */ (function (_super) {
  31326. __extends(Box, _super);
  31327. // Members
  31328. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31329. if (mesh === void 0) { mesh = null; }
  31330. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31332. _this.size = size;
  31333. _this.side = side;
  31334. return _this;
  31335. }
  31336. Box.prototype._regenerateVertexData = function () {
  31337. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31338. };
  31339. Box.prototype.copy = function (id) {
  31340. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31341. };
  31342. Box.prototype.serialize = function () {
  31343. var serializationObject = _super.prototype.serialize.call(this);
  31344. serializationObject.size = this.size;
  31345. return serializationObject;
  31346. };
  31347. Box.Parse = function (parsedBox, scene) {
  31348. if (scene.getGeometryByID(parsedBox.id)) {
  31349. return null; // null since geometry could be something else than a box...
  31350. }
  31351. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31352. if (BABYLON.Tags) {
  31353. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31354. }
  31355. scene.pushGeometry(box, true);
  31356. return box;
  31357. };
  31358. return Box;
  31359. }(_Primitive));
  31360. Primitives.Box = Box;
  31361. var Sphere = /** @class */ (function (_super) {
  31362. __extends(Sphere, _super);
  31363. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31364. if (mesh === void 0) { mesh = null; }
  31365. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31366. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31367. _this.segments = segments;
  31368. _this.diameter = diameter;
  31369. _this.side = side;
  31370. return _this;
  31371. }
  31372. Sphere.prototype._regenerateVertexData = function () {
  31373. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31374. };
  31375. Sphere.prototype.copy = function (id) {
  31376. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31377. };
  31378. Sphere.prototype.serialize = function () {
  31379. var serializationObject = _super.prototype.serialize.call(this);
  31380. serializationObject.segments = this.segments;
  31381. serializationObject.diameter = this.diameter;
  31382. return serializationObject;
  31383. };
  31384. Sphere.Parse = function (parsedSphere, scene) {
  31385. if (scene.getGeometryByID(parsedSphere.id)) {
  31386. return null; // null since geometry could be something else than a sphere...
  31387. }
  31388. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31389. if (BABYLON.Tags) {
  31390. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31391. }
  31392. scene.pushGeometry(sphere, true);
  31393. return sphere;
  31394. };
  31395. return Sphere;
  31396. }(_Primitive));
  31397. Primitives.Sphere = Sphere;
  31398. var Disc = /** @class */ (function (_super) {
  31399. __extends(Disc, _super);
  31400. // Members
  31401. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31402. if (mesh === void 0) { mesh = null; }
  31403. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31404. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31405. _this.radius = radius;
  31406. _this.tessellation = tessellation;
  31407. _this.side = side;
  31408. return _this;
  31409. }
  31410. Disc.prototype._regenerateVertexData = function () {
  31411. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31412. };
  31413. Disc.prototype.copy = function (id) {
  31414. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31415. };
  31416. return Disc;
  31417. }(_Primitive));
  31418. Primitives.Disc = Disc;
  31419. var Cylinder = /** @class */ (function (_super) {
  31420. __extends(Cylinder, _super);
  31421. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31422. if (subdivisions === void 0) { subdivisions = 1; }
  31423. if (mesh === void 0) { mesh = null; }
  31424. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31425. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31426. _this.height = height;
  31427. _this.diameterTop = diameterTop;
  31428. _this.diameterBottom = diameterBottom;
  31429. _this.tessellation = tessellation;
  31430. _this.subdivisions = subdivisions;
  31431. _this.side = side;
  31432. return _this;
  31433. }
  31434. Cylinder.prototype._regenerateVertexData = function () {
  31435. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31436. };
  31437. Cylinder.prototype.copy = function (id) {
  31438. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31439. };
  31440. Cylinder.prototype.serialize = function () {
  31441. var serializationObject = _super.prototype.serialize.call(this);
  31442. serializationObject.height = this.height;
  31443. serializationObject.diameterTop = this.diameterTop;
  31444. serializationObject.diameterBottom = this.diameterBottom;
  31445. serializationObject.tessellation = this.tessellation;
  31446. return serializationObject;
  31447. };
  31448. Cylinder.Parse = function (parsedCylinder, scene) {
  31449. if (scene.getGeometryByID(parsedCylinder.id)) {
  31450. return null; // null since geometry could be something else than a cylinder...
  31451. }
  31452. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31453. if (BABYLON.Tags) {
  31454. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31455. }
  31456. scene.pushGeometry(cylinder, true);
  31457. return cylinder;
  31458. };
  31459. return Cylinder;
  31460. }(_Primitive));
  31461. Primitives.Cylinder = Cylinder;
  31462. var Torus = /** @class */ (function (_super) {
  31463. __extends(Torus, _super);
  31464. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31465. if (mesh === void 0) { mesh = null; }
  31466. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31467. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31468. _this.diameter = diameter;
  31469. _this.thickness = thickness;
  31470. _this.tessellation = tessellation;
  31471. _this.side = side;
  31472. return _this;
  31473. }
  31474. Torus.prototype._regenerateVertexData = function () {
  31475. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31476. };
  31477. Torus.prototype.copy = function (id) {
  31478. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31479. };
  31480. Torus.prototype.serialize = function () {
  31481. var serializationObject = _super.prototype.serialize.call(this);
  31482. serializationObject.diameter = this.diameter;
  31483. serializationObject.thickness = this.thickness;
  31484. serializationObject.tessellation = this.tessellation;
  31485. return serializationObject;
  31486. };
  31487. Torus.Parse = function (parsedTorus, scene) {
  31488. if (scene.getGeometryByID(parsedTorus.id)) {
  31489. return null; // null since geometry could be something else than a torus...
  31490. }
  31491. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31492. if (BABYLON.Tags) {
  31493. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31494. }
  31495. scene.pushGeometry(torus, true);
  31496. return torus;
  31497. };
  31498. return Torus;
  31499. }(_Primitive));
  31500. Primitives.Torus = Torus;
  31501. var Ground = /** @class */ (function (_super) {
  31502. __extends(Ground, _super);
  31503. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31504. if (mesh === void 0) { mesh = null; }
  31505. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31506. _this.width = width;
  31507. _this.height = height;
  31508. _this.subdivisions = subdivisions;
  31509. return _this;
  31510. }
  31511. Ground.prototype._regenerateVertexData = function () {
  31512. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31513. };
  31514. Ground.prototype.copy = function (id) {
  31515. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31516. };
  31517. Ground.prototype.serialize = function () {
  31518. var serializationObject = _super.prototype.serialize.call(this);
  31519. serializationObject.width = this.width;
  31520. serializationObject.height = this.height;
  31521. serializationObject.subdivisions = this.subdivisions;
  31522. return serializationObject;
  31523. };
  31524. Ground.Parse = function (parsedGround, scene) {
  31525. if (scene.getGeometryByID(parsedGround.id)) {
  31526. return null; // null since geometry could be something else than a ground...
  31527. }
  31528. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31529. if (BABYLON.Tags) {
  31530. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31531. }
  31532. scene.pushGeometry(ground, true);
  31533. return ground;
  31534. };
  31535. return Ground;
  31536. }(_Primitive));
  31537. Primitives.Ground = Ground;
  31538. var TiledGround = /** @class */ (function (_super) {
  31539. __extends(TiledGround, _super);
  31540. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31541. if (mesh === void 0) { mesh = null; }
  31542. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31543. _this.xmin = xmin;
  31544. _this.zmin = zmin;
  31545. _this.xmax = xmax;
  31546. _this.zmax = zmax;
  31547. _this.subdivisions = subdivisions;
  31548. _this.precision = precision;
  31549. return _this;
  31550. }
  31551. TiledGround.prototype._regenerateVertexData = function () {
  31552. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31553. };
  31554. TiledGround.prototype.copy = function (id) {
  31555. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31556. };
  31557. return TiledGround;
  31558. }(_Primitive));
  31559. Primitives.TiledGround = TiledGround;
  31560. var Plane = /** @class */ (function (_super) {
  31561. __extends(Plane, _super);
  31562. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31563. if (mesh === void 0) { mesh = null; }
  31564. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31565. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31566. _this.size = size;
  31567. _this.side = side;
  31568. return _this;
  31569. }
  31570. Plane.prototype._regenerateVertexData = function () {
  31571. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31572. };
  31573. Plane.prototype.copy = function (id) {
  31574. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31575. };
  31576. Plane.prototype.serialize = function () {
  31577. var serializationObject = _super.prototype.serialize.call(this);
  31578. serializationObject.size = this.size;
  31579. return serializationObject;
  31580. };
  31581. Plane.Parse = function (parsedPlane, scene) {
  31582. if (scene.getGeometryByID(parsedPlane.id)) {
  31583. return null; // null since geometry could be something else than a ground...
  31584. }
  31585. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31586. if (BABYLON.Tags) {
  31587. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31588. }
  31589. scene.pushGeometry(plane, true);
  31590. return plane;
  31591. };
  31592. return Plane;
  31593. }(_Primitive));
  31594. Primitives.Plane = Plane;
  31595. var TorusKnot = /** @class */ (function (_super) {
  31596. __extends(TorusKnot, _super);
  31597. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31598. if (mesh === void 0) { mesh = null; }
  31599. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31600. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31601. _this.radius = radius;
  31602. _this.tube = tube;
  31603. _this.radialSegments = radialSegments;
  31604. _this.tubularSegments = tubularSegments;
  31605. _this.p = p;
  31606. _this.q = q;
  31607. _this.side = side;
  31608. return _this;
  31609. }
  31610. TorusKnot.prototype._regenerateVertexData = function () {
  31611. 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 });
  31612. };
  31613. TorusKnot.prototype.copy = function (id) {
  31614. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31615. };
  31616. TorusKnot.prototype.serialize = function () {
  31617. var serializationObject = _super.prototype.serialize.call(this);
  31618. serializationObject.radius = this.radius;
  31619. serializationObject.tube = this.tube;
  31620. serializationObject.radialSegments = this.radialSegments;
  31621. serializationObject.tubularSegments = this.tubularSegments;
  31622. serializationObject.p = this.p;
  31623. serializationObject.q = this.q;
  31624. return serializationObject;
  31625. };
  31626. ;
  31627. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31628. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31629. return null; // null since geometry could be something else than a ground...
  31630. }
  31631. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31632. if (BABYLON.Tags) {
  31633. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31634. }
  31635. scene.pushGeometry(torusKnot, true);
  31636. return torusKnot;
  31637. };
  31638. return TorusKnot;
  31639. }(_Primitive));
  31640. Primitives.TorusKnot = TorusKnot;
  31641. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31642. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31643. })(BABYLON || (BABYLON = {}));
  31644. //# sourceMappingURL=babylon.geometry.js.map
  31645. var BABYLON;
  31646. (function (BABYLON) {
  31647. var PostProcessManager = /** @class */ (function () {
  31648. function PostProcessManager(scene) {
  31649. this._vertexBuffers = {};
  31650. this._scene = scene;
  31651. }
  31652. PostProcessManager.prototype._prepareBuffers = function () {
  31653. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31654. return;
  31655. }
  31656. // VBO
  31657. var vertices = [];
  31658. vertices.push(1, 1);
  31659. vertices.push(-1, 1);
  31660. vertices.push(-1, -1);
  31661. vertices.push(1, -1);
  31662. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31663. this._buildIndexBuffer();
  31664. };
  31665. PostProcessManager.prototype._buildIndexBuffer = function () {
  31666. // Indices
  31667. var indices = [];
  31668. indices.push(0);
  31669. indices.push(1);
  31670. indices.push(2);
  31671. indices.push(0);
  31672. indices.push(2);
  31673. indices.push(3);
  31674. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31675. };
  31676. PostProcessManager.prototype._rebuild = function () {
  31677. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31678. if (!vb) {
  31679. return;
  31680. }
  31681. vb._rebuild();
  31682. this._buildIndexBuffer();
  31683. };
  31684. // Methods
  31685. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31686. if (sourceTexture === void 0) { sourceTexture = null; }
  31687. if (postProcesses === void 0) { postProcesses = null; }
  31688. var camera = this._scene.activeCamera;
  31689. if (!camera) {
  31690. return false;
  31691. }
  31692. var postProcesses = postProcesses || camera._postProcesses;
  31693. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31694. return false;
  31695. }
  31696. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31697. return true;
  31698. };
  31699. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31700. if (targetTexture === void 0) { targetTexture = null; }
  31701. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31702. if (!this._scene.activeCamera) {
  31703. return;
  31704. }
  31705. var engine = this._scene.getEngine();
  31706. for (var index = 0; index < postProcesses.length; index++) {
  31707. if (index < postProcesses.length - 1) {
  31708. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31709. }
  31710. else {
  31711. if (targetTexture) {
  31712. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31713. }
  31714. else {
  31715. engine.restoreDefaultFramebuffer();
  31716. }
  31717. }
  31718. var pp = postProcesses[index];
  31719. var effect = pp.apply();
  31720. if (effect) {
  31721. pp.onBeforeRenderObservable.notifyObservers(effect);
  31722. // VBOs
  31723. this._prepareBuffers();
  31724. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31725. // Draw order
  31726. engine.draw(true, 0, 6);
  31727. pp.onAfterRenderObservable.notifyObservers(effect);
  31728. }
  31729. }
  31730. // Restore depth buffer
  31731. engine.setDepthBuffer(true);
  31732. engine.setDepthWrite(true);
  31733. };
  31734. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31735. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31736. var camera = this._scene.activeCamera;
  31737. if (!camera) {
  31738. return;
  31739. }
  31740. postProcesses = postProcesses || camera._postProcesses;
  31741. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31742. return;
  31743. }
  31744. var engine = this._scene.getEngine();
  31745. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31746. if (index < len - 1) {
  31747. postProcesses[index + 1].activate(camera, targetTexture);
  31748. }
  31749. else {
  31750. if (targetTexture) {
  31751. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31752. }
  31753. else {
  31754. engine.restoreDefaultFramebuffer();
  31755. }
  31756. }
  31757. if (doNotPresent) {
  31758. break;
  31759. }
  31760. var pp = postProcesses[index];
  31761. var effect = pp.apply();
  31762. if (effect) {
  31763. pp.onBeforeRenderObservable.notifyObservers(effect);
  31764. // VBOs
  31765. this._prepareBuffers();
  31766. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31767. // Draw order
  31768. engine.draw(true, 0, 6);
  31769. pp.onAfterRenderObservable.notifyObservers(effect);
  31770. }
  31771. }
  31772. // Restore states
  31773. engine.setDepthBuffer(true);
  31774. engine.setDepthWrite(true);
  31775. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31776. };
  31777. PostProcessManager.prototype.dispose = function () {
  31778. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31779. if (buffer) {
  31780. buffer.dispose();
  31781. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31782. }
  31783. if (this._indexBuffer) {
  31784. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31785. this._indexBuffer = null;
  31786. }
  31787. };
  31788. return PostProcessManager;
  31789. }());
  31790. BABYLON.PostProcessManager = PostProcessManager;
  31791. })(BABYLON || (BABYLON = {}));
  31792. //# sourceMappingURL=babylon.postProcessManager.js.map
  31793. var BABYLON;
  31794. (function (BABYLON) {
  31795. /**
  31796. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31797. */
  31798. var PerformanceMonitor = /** @class */ (function () {
  31799. /**
  31800. * constructor
  31801. * @param frameSampleSize The number of samples required to saturate the sliding window
  31802. */
  31803. function PerformanceMonitor(frameSampleSize) {
  31804. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31805. this._enabled = true;
  31806. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31807. }
  31808. /**
  31809. * Samples current frame
  31810. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31811. */
  31812. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31813. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31814. if (!this._enabled)
  31815. return;
  31816. if (this._lastFrameTimeMs != null) {
  31817. var dt = timeMs - this._lastFrameTimeMs;
  31818. this._rollingFrameTime.add(dt);
  31819. }
  31820. this._lastFrameTimeMs = timeMs;
  31821. };
  31822. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31823. /**
  31824. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31825. * @return Average frame time in milliseconds
  31826. */
  31827. get: function () {
  31828. return this._rollingFrameTime.average;
  31829. },
  31830. enumerable: true,
  31831. configurable: true
  31832. });
  31833. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31834. /**
  31835. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31836. * @return Frame time variance in milliseconds squared
  31837. */
  31838. get: function () {
  31839. return this._rollingFrameTime.variance;
  31840. },
  31841. enumerable: true,
  31842. configurable: true
  31843. });
  31844. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31845. /**
  31846. * Returns the frame time of the most recent frame
  31847. * @return Frame time in milliseconds
  31848. */
  31849. get: function () {
  31850. return this._rollingFrameTime.history(0);
  31851. },
  31852. enumerable: true,
  31853. configurable: true
  31854. });
  31855. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31856. /**
  31857. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31858. * @return Framerate in frames per second
  31859. */
  31860. get: function () {
  31861. return 1000.0 / this._rollingFrameTime.average;
  31862. },
  31863. enumerable: true,
  31864. configurable: true
  31865. });
  31866. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31867. /**
  31868. * Returns the average framerate in frames per second using the most recent frame time
  31869. * @return Framerate in frames per second
  31870. */
  31871. get: function () {
  31872. var history = this._rollingFrameTime.history(0);
  31873. if (history === 0) {
  31874. return 0;
  31875. }
  31876. return 1000.0 / history;
  31877. },
  31878. enumerable: true,
  31879. configurable: true
  31880. });
  31881. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31882. /**
  31883. * Returns true if enough samples have been taken to completely fill the sliding window
  31884. * @return true if saturated
  31885. */
  31886. get: function () {
  31887. return this._rollingFrameTime.isSaturated();
  31888. },
  31889. enumerable: true,
  31890. configurable: true
  31891. });
  31892. /**
  31893. * Enables contributions to the sliding window sample set
  31894. */
  31895. PerformanceMonitor.prototype.enable = function () {
  31896. this._enabled = true;
  31897. };
  31898. /**
  31899. * Disables contributions to the sliding window sample set
  31900. * Samples will not be interpolated over the disabled period
  31901. */
  31902. PerformanceMonitor.prototype.disable = function () {
  31903. this._enabled = false;
  31904. //clear last sample to avoid interpolating over the disabled period when next enabled
  31905. this._lastFrameTimeMs = null;
  31906. this._lastChangeTimeMs = null;
  31907. };
  31908. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31909. /**
  31910. * Returns true if sampling is enabled
  31911. * @return true if enabled
  31912. */
  31913. get: function () {
  31914. return this._enabled;
  31915. },
  31916. enumerable: true,
  31917. configurable: true
  31918. });
  31919. /**
  31920. * Resets performance monitor
  31921. */
  31922. PerformanceMonitor.prototype.reset = function () {
  31923. //clear last sample to avoid interpolating over the disabled period when next enabled
  31924. this._lastFrameTimeMs = null;
  31925. this._lastChangeTimeMs = null;
  31926. //wipe record
  31927. this._rollingFrameTime.reset();
  31928. };
  31929. return PerformanceMonitor;
  31930. }());
  31931. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31932. /**
  31933. * RollingAverage
  31934. *
  31935. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31936. */
  31937. var RollingAverage = /** @class */ (function () {
  31938. /**
  31939. * constructor
  31940. * @param length The number of samples required to saturate the sliding window
  31941. */
  31942. function RollingAverage(length) {
  31943. this._samples = new Array(length);
  31944. this.reset();
  31945. }
  31946. /**
  31947. * Adds a sample to the sample set
  31948. * @param v The sample value
  31949. */
  31950. RollingAverage.prototype.add = function (v) {
  31951. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31952. var delta;
  31953. //we need to check if we've already wrapped round
  31954. if (this.isSaturated()) {
  31955. //remove bottom of stack from mean
  31956. var bottomValue = this._samples[this._pos];
  31957. delta = bottomValue - this.average;
  31958. this.average -= delta / (this._sampleCount - 1);
  31959. this._m2 -= delta * (bottomValue - this.average);
  31960. }
  31961. else {
  31962. this._sampleCount++;
  31963. }
  31964. //add new value to mean
  31965. delta = v - this.average;
  31966. this.average += delta / (this._sampleCount);
  31967. this._m2 += delta * (v - this.average);
  31968. //set the new variance
  31969. this.variance = this._m2 / (this._sampleCount - 1);
  31970. this._samples[this._pos] = v;
  31971. this._pos++;
  31972. this._pos %= this._samples.length; //positive wrap around
  31973. };
  31974. /**
  31975. * Returns previously added values or null if outside of history or outside the sliding window domain
  31976. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31977. * @return Value previously recorded with add() or null if outside of range
  31978. */
  31979. RollingAverage.prototype.history = function (i) {
  31980. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31981. return 0;
  31982. }
  31983. var i0 = this._wrapPosition(this._pos - 1.0);
  31984. return this._samples[this._wrapPosition(i0 - i)];
  31985. };
  31986. /**
  31987. * Returns true if enough samples have been taken to completely fill the sliding window
  31988. * @return true if sample-set saturated
  31989. */
  31990. RollingAverage.prototype.isSaturated = function () {
  31991. return this._sampleCount >= this._samples.length;
  31992. };
  31993. /**
  31994. * Resets the rolling average (equivalent to 0 samples taken so far)
  31995. */
  31996. RollingAverage.prototype.reset = function () {
  31997. this.average = 0;
  31998. this.variance = 0;
  31999. this._sampleCount = 0;
  32000. this._pos = 0;
  32001. this._m2 = 0;
  32002. };
  32003. /**
  32004. * Wraps a value around the sample range boundaries
  32005. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32006. * @return Wrapped position in sample range
  32007. */
  32008. RollingAverage.prototype._wrapPosition = function (i) {
  32009. var max = this._samples.length;
  32010. return ((i % max) + max) % max;
  32011. };
  32012. return RollingAverage;
  32013. }());
  32014. BABYLON.RollingAverage = RollingAverage;
  32015. })(BABYLON || (BABYLON = {}));
  32016. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32017. var BABYLON;
  32018. (function (BABYLON) {
  32019. /**
  32020. * This groups together the common properties used for image processing either in direct forward pass
  32021. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32022. * or not.
  32023. */
  32024. var ImageProcessingConfiguration = /** @class */ (function () {
  32025. function ImageProcessingConfiguration() {
  32026. /**
  32027. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32028. */
  32029. this.colorCurves = new BABYLON.ColorCurves();
  32030. this._colorCurvesEnabled = false;
  32031. this._colorGradingEnabled = false;
  32032. this._colorGradingWithGreenDepth = true;
  32033. this._colorGradingBGR = true;
  32034. this._exposure = 1.0;
  32035. this._toneMappingEnabled = false;
  32036. this._contrast = 1.0;
  32037. /**
  32038. * Vignette stretch size.
  32039. */
  32040. this.vignetteStretch = 0;
  32041. /**
  32042. * Vignette centre X Offset.
  32043. */
  32044. this.vignetteCentreX = 0;
  32045. /**
  32046. * Vignette centre Y Offset.
  32047. */
  32048. this.vignetteCentreY = 0;
  32049. /**
  32050. * Vignette weight or intensity of the vignette effect.
  32051. */
  32052. this.vignetteWeight = 1.5;
  32053. /**
  32054. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32055. * if vignetteEnabled is set to true.
  32056. */
  32057. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32058. /**
  32059. * Camera field of view used by the Vignette effect.
  32060. */
  32061. this.vignetteCameraFov = 0.5;
  32062. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32063. this._vignetteEnabled = false;
  32064. this._applyByPostProcess = false;
  32065. /**
  32066. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32067. * @type {BABYLON.Observable}
  32068. */
  32069. this.onUpdateParameters = new BABYLON.Observable();
  32070. }
  32071. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32072. /**
  32073. * Gets wether the color curves effect is enabled.
  32074. */
  32075. get: function () {
  32076. return this._colorCurvesEnabled;
  32077. },
  32078. /**
  32079. * Sets wether the color curves effect is enabled.
  32080. */
  32081. set: function (value) {
  32082. if (this._colorCurvesEnabled === value) {
  32083. return;
  32084. }
  32085. this._colorCurvesEnabled = value;
  32086. this._updateParameters();
  32087. },
  32088. enumerable: true,
  32089. configurable: true
  32090. });
  32091. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32092. /**
  32093. * Gets wether the color grading effect is enabled.
  32094. */
  32095. get: function () {
  32096. return this._colorGradingEnabled;
  32097. },
  32098. /**
  32099. * Sets wether the color grading effect is enabled.
  32100. */
  32101. set: function (value) {
  32102. if (this._colorGradingEnabled === value) {
  32103. return;
  32104. }
  32105. this._colorGradingEnabled = value;
  32106. this._updateParameters();
  32107. },
  32108. enumerable: true,
  32109. configurable: true
  32110. });
  32111. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32112. /**
  32113. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32114. */
  32115. get: function () {
  32116. return this._colorGradingWithGreenDepth;
  32117. },
  32118. /**
  32119. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32120. */
  32121. set: function (value) {
  32122. if (this._colorGradingWithGreenDepth === value) {
  32123. return;
  32124. }
  32125. this._colorGradingWithGreenDepth = value;
  32126. this._updateParameters();
  32127. },
  32128. enumerable: true,
  32129. configurable: true
  32130. });
  32131. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32132. /**
  32133. * Gets wether the color grading texture contains BGR values.
  32134. */
  32135. get: function () {
  32136. return this._colorGradingBGR;
  32137. },
  32138. /**
  32139. * Sets wether the color grading texture contains BGR values.
  32140. */
  32141. set: function (value) {
  32142. if (this._colorGradingBGR === value) {
  32143. return;
  32144. }
  32145. this._colorGradingBGR = value;
  32146. this._updateParameters();
  32147. },
  32148. enumerable: true,
  32149. configurable: true
  32150. });
  32151. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32152. /**
  32153. * Gets the Exposure used in the effect.
  32154. */
  32155. get: function () {
  32156. return this._exposure;
  32157. },
  32158. /**
  32159. * Sets the Exposure used in the effect.
  32160. */
  32161. set: function (value) {
  32162. if (this._exposure === value) {
  32163. return;
  32164. }
  32165. this._exposure = value;
  32166. this._updateParameters();
  32167. },
  32168. enumerable: true,
  32169. configurable: true
  32170. });
  32171. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32172. /**
  32173. * Gets wether the tone mapping effect is enabled.
  32174. */
  32175. get: function () {
  32176. return this._toneMappingEnabled;
  32177. },
  32178. /**
  32179. * Sets wether the tone mapping effect is enabled.
  32180. */
  32181. set: function (value) {
  32182. if (this._toneMappingEnabled === value) {
  32183. return;
  32184. }
  32185. this._toneMappingEnabled = value;
  32186. this._updateParameters();
  32187. },
  32188. enumerable: true,
  32189. configurable: true
  32190. });
  32191. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32192. /**
  32193. * Gets the contrast used in the effect.
  32194. */
  32195. get: function () {
  32196. return this._contrast;
  32197. },
  32198. /**
  32199. * Sets the contrast used in the effect.
  32200. */
  32201. set: function (value) {
  32202. if (this._contrast === value) {
  32203. return;
  32204. }
  32205. this._contrast = value;
  32206. this._updateParameters();
  32207. },
  32208. enumerable: true,
  32209. configurable: true
  32210. });
  32211. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32212. /**
  32213. * Gets the vignette blend mode allowing different kind of effect.
  32214. */
  32215. get: function () {
  32216. return this._vignetteBlendMode;
  32217. },
  32218. /**
  32219. * Sets the vignette blend mode allowing different kind of effect.
  32220. */
  32221. set: function (value) {
  32222. if (this._vignetteBlendMode === value) {
  32223. return;
  32224. }
  32225. this._vignetteBlendMode = value;
  32226. this._updateParameters();
  32227. },
  32228. enumerable: true,
  32229. configurable: true
  32230. });
  32231. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32232. /**
  32233. * Gets wether the vignette effect is enabled.
  32234. */
  32235. get: function () {
  32236. return this._vignetteEnabled;
  32237. },
  32238. /**
  32239. * Sets wether the vignette effect is enabled.
  32240. */
  32241. set: function (value) {
  32242. if (this._vignetteEnabled === value) {
  32243. return;
  32244. }
  32245. this._vignetteEnabled = value;
  32246. this._updateParameters();
  32247. },
  32248. enumerable: true,
  32249. configurable: true
  32250. });
  32251. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32252. /**
  32253. * Gets wether the image processing is applied through a post process or not.
  32254. */
  32255. get: function () {
  32256. return this._applyByPostProcess;
  32257. },
  32258. /**
  32259. * Sets wether the image processing is applied through a post process or not.
  32260. */
  32261. set: function (value) {
  32262. if (this._applyByPostProcess === value) {
  32263. return;
  32264. }
  32265. this._applyByPostProcess = value;
  32266. this._updateParameters();
  32267. },
  32268. enumerable: true,
  32269. configurable: true
  32270. });
  32271. /**
  32272. * Method called each time the image processing information changes requires to recompile the effect.
  32273. */
  32274. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32275. this.onUpdateParameters.notifyObservers(this);
  32276. };
  32277. ImageProcessingConfiguration.prototype.getClassName = function () {
  32278. return "ImageProcessingConfiguration";
  32279. };
  32280. /**
  32281. * Prepare the list of uniforms associated with the Image Processing effects.
  32282. * @param uniformsList The list of uniforms used in the effect
  32283. * @param defines the list of defines currently in use
  32284. */
  32285. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32286. if (defines.EXPOSURE) {
  32287. uniforms.push("exposureLinear");
  32288. }
  32289. if (defines.CONTRAST) {
  32290. uniforms.push("contrast");
  32291. }
  32292. if (defines.COLORGRADING) {
  32293. uniforms.push("colorTransformSettings");
  32294. }
  32295. if (defines.VIGNETTE) {
  32296. uniforms.push("vInverseScreenSize");
  32297. uniforms.push("vignetteSettings1");
  32298. uniforms.push("vignetteSettings2");
  32299. }
  32300. if (defines.COLORCURVES) {
  32301. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32302. }
  32303. };
  32304. /**
  32305. * Prepare the list of samplers associated with the Image Processing effects.
  32306. * @param uniformsList The list of uniforms used in the effect
  32307. * @param defines the list of defines currently in use
  32308. */
  32309. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32310. if (defines.COLORGRADING) {
  32311. samplersList.push("txColorTransform");
  32312. }
  32313. };
  32314. /**
  32315. * Prepare the list of defines associated to the shader.
  32316. * @param defines the list of defines to complete
  32317. */
  32318. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32319. if (forPostProcess === void 0) { forPostProcess = false; }
  32320. if (forPostProcess !== this.applyByPostProcess) {
  32321. defines.VIGNETTE = false;
  32322. defines.TONEMAPPING = false;
  32323. defines.CONTRAST = false;
  32324. defines.EXPOSURE = false;
  32325. defines.COLORCURVES = false;
  32326. defines.COLORGRADING = false;
  32327. defines.COLORGRADING3D = false;
  32328. defines.IMAGEPROCESSING = false;
  32329. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32330. return;
  32331. }
  32332. defines.VIGNETTE = this.vignetteEnabled;
  32333. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32334. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32335. defines.TONEMAPPING = this.toneMappingEnabled;
  32336. defines.CONTRAST = (this.contrast !== 1.0);
  32337. defines.EXPOSURE = (this.exposure !== 1.0);
  32338. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32339. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32340. if (defines.COLORGRADING) {
  32341. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32342. }
  32343. else {
  32344. defines.COLORGRADING3D = false;
  32345. }
  32346. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32347. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32348. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32349. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32350. };
  32351. /**
  32352. * Returns true if all the image processing information are ready.
  32353. */
  32354. ImageProcessingConfiguration.prototype.isReady = function () {
  32355. // Color Grading texure can not be none blocking.
  32356. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32357. };
  32358. /**
  32359. * Binds the image processing to the shader.
  32360. * @param effect The effect to bind to
  32361. */
  32362. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32363. if (aspectRatio === void 0) { aspectRatio = 1; }
  32364. // Color Curves
  32365. if (this._colorCurvesEnabled && this.colorCurves) {
  32366. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32367. }
  32368. // Vignette
  32369. if (this._vignetteEnabled) {
  32370. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32371. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32372. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32373. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32374. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32375. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32376. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32377. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32378. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32379. var vignettePower = -2.0 * this.vignetteWeight;
  32380. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32381. }
  32382. // Exposure
  32383. effect.setFloat("exposureLinear", this.exposure);
  32384. // Contrast
  32385. effect.setFloat("contrast", this.contrast);
  32386. // Color transform settings
  32387. if (this.colorGradingTexture) {
  32388. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32389. var textureSize = this.colorGradingTexture.getSize().height;
  32390. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32391. 0.5 / textureSize, // textureOffset
  32392. textureSize, // textureSize
  32393. this.colorGradingTexture.level // weight
  32394. );
  32395. }
  32396. };
  32397. /**
  32398. * Clones the current image processing instance.
  32399. * @return The cloned image processing
  32400. */
  32401. ImageProcessingConfiguration.prototype.clone = function () {
  32402. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32403. };
  32404. /**
  32405. * Serializes the current image processing instance to a json representation.
  32406. * @return a JSON representation
  32407. */
  32408. ImageProcessingConfiguration.prototype.serialize = function () {
  32409. return BABYLON.SerializationHelper.Serialize(this);
  32410. };
  32411. /**
  32412. * Parses the image processing from a json representation.
  32413. * @param source the JSON source to parse
  32414. * @return The parsed image processing
  32415. */
  32416. ImageProcessingConfiguration.Parse = function (source) {
  32417. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32418. };
  32419. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32420. /**
  32421. * Used to apply the vignette as a mix with the pixel color.
  32422. */
  32423. get: function () {
  32424. return this._VIGNETTEMODE_MULTIPLY;
  32425. },
  32426. enumerable: true,
  32427. configurable: true
  32428. });
  32429. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32430. /**
  32431. * Used to apply the vignette as a replacement of the pixel color.
  32432. */
  32433. get: function () {
  32434. return this._VIGNETTEMODE_OPAQUE;
  32435. },
  32436. enumerable: true,
  32437. configurable: true
  32438. });
  32439. // Static constants associated to the image processing.
  32440. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32441. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32442. __decorate([
  32443. BABYLON.serializeAsColorCurves()
  32444. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32445. __decorate([
  32446. BABYLON.serialize()
  32447. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32448. __decorate([
  32449. BABYLON.serializeAsTexture()
  32450. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32451. __decorate([
  32452. BABYLON.serialize()
  32453. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32454. __decorate([
  32455. BABYLON.serialize()
  32456. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32457. __decorate([
  32458. BABYLON.serialize()
  32459. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32460. __decorate([
  32461. BABYLON.serialize()
  32462. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32463. __decorate([
  32464. BABYLON.serialize()
  32465. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32466. __decorate([
  32467. BABYLON.serialize()
  32468. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32469. __decorate([
  32470. BABYLON.serialize()
  32471. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32472. __decorate([
  32473. BABYLON.serialize()
  32474. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32475. __decorate([
  32476. BABYLON.serialize()
  32477. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32478. __decorate([
  32479. BABYLON.serialize()
  32480. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32481. __decorate([
  32482. BABYLON.serializeAsColor4()
  32483. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32484. __decorate([
  32485. BABYLON.serialize()
  32486. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32487. __decorate([
  32488. BABYLON.serialize()
  32489. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32490. __decorate([
  32491. BABYLON.serialize()
  32492. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32493. __decorate([
  32494. BABYLON.serialize()
  32495. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32496. return ImageProcessingConfiguration;
  32497. }());
  32498. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32499. })(BABYLON || (BABYLON = {}));
  32500. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32501. var BABYLON;
  32502. (function (BABYLON) {
  32503. /**
  32504. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32505. * It can help converting any input color in a desired output one. This can then be used to create effects
  32506. * from sepia, black and white to sixties or futuristic rendering...
  32507. *
  32508. * The only supported format is currently 3dl.
  32509. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32510. */
  32511. var ColorGradingTexture = /** @class */ (function (_super) {
  32512. __extends(ColorGradingTexture, _super);
  32513. /**
  32514. * Instantiates a ColorGradingTexture from the following parameters.
  32515. *
  32516. * @param url The location of the color gradind data (currently only supporting 3dl)
  32517. * @param scene The scene the texture will be used in
  32518. */
  32519. function ColorGradingTexture(url, scene) {
  32520. var _this = _super.call(this, scene) || this;
  32521. if (!url) {
  32522. return _this;
  32523. }
  32524. _this._engine = scene.getEngine();
  32525. _this._textureMatrix = BABYLON.Matrix.Identity();
  32526. _this.name = url;
  32527. _this.url = url;
  32528. _this.hasAlpha = false;
  32529. _this.isCube = false;
  32530. _this.is3D = _this._engine.webGLVersion > 1;
  32531. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32532. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32533. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32534. _this.anisotropicFilteringLevel = 1;
  32535. _this._texture = _this._getFromCache(url, true);
  32536. if (!_this._texture) {
  32537. if (!scene.useDelayedTextureLoading) {
  32538. _this.loadTexture();
  32539. }
  32540. else {
  32541. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32542. }
  32543. }
  32544. return _this;
  32545. }
  32546. /**
  32547. * Returns the texture matrix used in most of the material.
  32548. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32549. */
  32550. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32551. return this._textureMatrix;
  32552. };
  32553. /**
  32554. * Occurs when the file being loaded is a .3dl LUT file.
  32555. */
  32556. ColorGradingTexture.prototype.load3dlTexture = function () {
  32557. var engine = this._engine;
  32558. var texture;
  32559. if (engine.webGLVersion === 1) {
  32560. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32561. }
  32562. else {
  32563. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32564. }
  32565. this._texture = texture;
  32566. var callback = function (text) {
  32567. var data = null;
  32568. var tempData = null;
  32569. var line;
  32570. var lines = text.split('\n');
  32571. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32572. var maxColor = 0;
  32573. for (var i = 0; i < lines.length; i++) {
  32574. line = lines[i];
  32575. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32576. continue;
  32577. if (line.indexOf('#') === 0)
  32578. continue;
  32579. var words = line.split(" ");
  32580. if (size === 0) {
  32581. // Number of space + one
  32582. size = words.length;
  32583. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32584. tempData = new Float32Array(size * size * size * 4);
  32585. continue;
  32586. }
  32587. if (size != 0) {
  32588. var r = Math.max(parseInt(words[0]), 0);
  32589. var g = Math.max(parseInt(words[1]), 0);
  32590. var b = Math.max(parseInt(words[2]), 0);
  32591. maxColor = Math.max(r, maxColor);
  32592. maxColor = Math.max(g, maxColor);
  32593. maxColor = Math.max(b, maxColor);
  32594. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32595. if (tempData) {
  32596. tempData[pixelStorageIndex + 0] = r;
  32597. tempData[pixelStorageIndex + 1] = g;
  32598. tempData[pixelStorageIndex + 2] = b;
  32599. }
  32600. pixelIndexSlice++;
  32601. if (pixelIndexSlice % size == 0) {
  32602. pixelIndexH++;
  32603. pixelIndexSlice = 0;
  32604. if (pixelIndexH % size == 0) {
  32605. pixelIndexW++;
  32606. pixelIndexH = 0;
  32607. }
  32608. }
  32609. }
  32610. }
  32611. if (tempData && data) {
  32612. for (var i = 0; i < tempData.length; i++) {
  32613. if (i > 0 && (i + 1) % 4 === 0) {
  32614. data[i] = 255;
  32615. }
  32616. else {
  32617. var value = tempData[i];
  32618. data[i] = (value / maxColor * 255);
  32619. }
  32620. }
  32621. }
  32622. if (texture.is3D) {
  32623. texture.updateSize(size, size, size);
  32624. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32625. }
  32626. else {
  32627. texture.updateSize(size * size, size);
  32628. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32629. }
  32630. };
  32631. BABYLON.Tools.LoadFile(this.url, callback);
  32632. return this._texture;
  32633. };
  32634. /**
  32635. * Starts the loading process of the texture.
  32636. */
  32637. ColorGradingTexture.prototype.loadTexture = function () {
  32638. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32639. this.load3dlTexture();
  32640. }
  32641. };
  32642. /**
  32643. * Clones the color gradind texture.
  32644. */
  32645. ColorGradingTexture.prototype.clone = function () {
  32646. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32647. // Base texture
  32648. newTexture.level = this.level;
  32649. return newTexture;
  32650. };
  32651. /**
  32652. * Called during delayed load for textures.
  32653. */
  32654. ColorGradingTexture.prototype.delayLoad = function () {
  32655. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32656. return;
  32657. }
  32658. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32659. this._texture = this._getFromCache(this.url, true);
  32660. if (!this._texture) {
  32661. this.loadTexture();
  32662. }
  32663. };
  32664. /**
  32665. * Parses a color grading texture serialized by Babylon.
  32666. * @param parsedTexture The texture information being parsedTexture
  32667. * @param scene The scene to load the texture in
  32668. * @param rootUrl The root url of the data assets to load
  32669. * @return A color gradind texture
  32670. */
  32671. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32672. var texture = null;
  32673. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32674. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32675. texture.name = parsedTexture.name;
  32676. texture.level = parsedTexture.level;
  32677. }
  32678. return texture;
  32679. };
  32680. /**
  32681. * Serializes the LUT texture to json format.
  32682. */
  32683. ColorGradingTexture.prototype.serialize = function () {
  32684. if (!this.name) {
  32685. return null;
  32686. }
  32687. var serializationObject = {};
  32688. serializationObject.name = this.name;
  32689. serializationObject.level = this.level;
  32690. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32691. return serializationObject;
  32692. };
  32693. /**
  32694. * Empty line regex stored for GC.
  32695. */
  32696. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32697. return ColorGradingTexture;
  32698. }(BABYLON.BaseTexture));
  32699. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32700. })(BABYLON || (BABYLON = {}));
  32701. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32702. var BABYLON;
  32703. (function (BABYLON) {
  32704. /**
  32705. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32706. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32707. * 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;
  32708. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32709. */
  32710. var ColorCurves = /** @class */ (function () {
  32711. function ColorCurves() {
  32712. this._dirty = true;
  32713. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32714. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32715. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32716. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32717. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32718. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32719. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32720. this._globalHue = 30;
  32721. this._globalDensity = 0;
  32722. this._globalSaturation = 0;
  32723. this._globalExposure = 0;
  32724. this._highlightsHue = 30;
  32725. this._highlightsDensity = 0;
  32726. this._highlightsSaturation = 0;
  32727. this._highlightsExposure = 0;
  32728. this._midtonesHue = 30;
  32729. this._midtonesDensity = 0;
  32730. this._midtonesSaturation = 0;
  32731. this._midtonesExposure = 0;
  32732. this._shadowsHue = 30;
  32733. this._shadowsDensity = 0;
  32734. this._shadowsSaturation = 0;
  32735. this._shadowsExposure = 0;
  32736. }
  32737. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32738. /**
  32739. * Gets the global Hue value.
  32740. * 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).
  32741. */
  32742. get: function () {
  32743. return this._globalHue;
  32744. },
  32745. /**
  32746. * Sets the global Hue value.
  32747. * 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).
  32748. */
  32749. set: function (value) {
  32750. this._globalHue = value;
  32751. this._dirty = true;
  32752. },
  32753. enumerable: true,
  32754. configurable: true
  32755. });
  32756. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32757. /**
  32758. * Gets the global Density value.
  32759. * 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.
  32760. * Values less than zero provide a filter of opposite hue.
  32761. */
  32762. get: function () {
  32763. return this._globalDensity;
  32764. },
  32765. /**
  32766. * Sets the global Density value.
  32767. * 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.
  32768. * Values less than zero provide a filter of opposite hue.
  32769. */
  32770. set: function (value) {
  32771. this._globalDensity = value;
  32772. this._dirty = true;
  32773. },
  32774. enumerable: true,
  32775. configurable: true
  32776. });
  32777. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32778. /**
  32779. * Gets the global Saturation value.
  32780. * 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.
  32781. */
  32782. get: function () {
  32783. return this._globalSaturation;
  32784. },
  32785. /**
  32786. * Sets the global Saturation value.
  32787. * 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.
  32788. */
  32789. set: function (value) {
  32790. this._globalSaturation = value;
  32791. this._dirty = true;
  32792. },
  32793. enumerable: true,
  32794. configurable: true
  32795. });
  32796. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32797. /**
  32798. * Gets the highlights Hue value.
  32799. * 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).
  32800. */
  32801. get: function () {
  32802. return this._highlightsHue;
  32803. },
  32804. /**
  32805. * Sets the highlights Hue value.
  32806. * 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).
  32807. */
  32808. set: function (value) {
  32809. this._highlightsHue = value;
  32810. this._dirty = true;
  32811. },
  32812. enumerable: true,
  32813. configurable: true
  32814. });
  32815. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32816. /**
  32817. * Gets the highlights Density value.
  32818. * 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.
  32819. * Values less than zero provide a filter of opposite hue.
  32820. */
  32821. get: function () {
  32822. return this._highlightsDensity;
  32823. },
  32824. /**
  32825. * Sets the highlights Density value.
  32826. * 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.
  32827. * Values less than zero provide a filter of opposite hue.
  32828. */
  32829. set: function (value) {
  32830. this._highlightsDensity = value;
  32831. this._dirty = true;
  32832. },
  32833. enumerable: true,
  32834. configurable: true
  32835. });
  32836. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32837. /**
  32838. * Gets the highlights Saturation value.
  32839. * 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.
  32840. */
  32841. get: function () {
  32842. return this._highlightsSaturation;
  32843. },
  32844. /**
  32845. * Sets the highlights Saturation value.
  32846. * 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.
  32847. */
  32848. set: function (value) {
  32849. this._highlightsSaturation = value;
  32850. this._dirty = true;
  32851. },
  32852. enumerable: true,
  32853. configurable: true
  32854. });
  32855. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32856. /**
  32857. * Gets the highlights Exposure value.
  32858. * 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.
  32859. */
  32860. get: function () {
  32861. return this._highlightsExposure;
  32862. },
  32863. /**
  32864. * Sets the highlights Exposure value.
  32865. * 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.
  32866. */
  32867. set: function (value) {
  32868. this._highlightsExposure = value;
  32869. this._dirty = true;
  32870. },
  32871. enumerable: true,
  32872. configurable: true
  32873. });
  32874. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32875. /**
  32876. * Gets the midtones Hue value.
  32877. * 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).
  32878. */
  32879. get: function () {
  32880. return this._midtonesHue;
  32881. },
  32882. /**
  32883. * Sets the midtones Hue value.
  32884. * 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).
  32885. */
  32886. set: function (value) {
  32887. this._midtonesHue = value;
  32888. this._dirty = true;
  32889. },
  32890. enumerable: true,
  32891. configurable: true
  32892. });
  32893. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32894. /**
  32895. * Gets the midtones Density value.
  32896. * 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.
  32897. * Values less than zero provide a filter of opposite hue.
  32898. */
  32899. get: function () {
  32900. return this._midtonesDensity;
  32901. },
  32902. /**
  32903. * Sets the midtones Density value.
  32904. * 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.
  32905. * Values less than zero provide a filter of opposite hue.
  32906. */
  32907. set: function (value) {
  32908. this._midtonesDensity = value;
  32909. this._dirty = true;
  32910. },
  32911. enumerable: true,
  32912. configurable: true
  32913. });
  32914. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32915. /**
  32916. * Gets the midtones Saturation value.
  32917. * 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.
  32918. */
  32919. get: function () {
  32920. return this._midtonesSaturation;
  32921. },
  32922. /**
  32923. * Sets the midtones Saturation value.
  32924. * 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.
  32925. */
  32926. set: function (value) {
  32927. this._midtonesSaturation = value;
  32928. this._dirty = true;
  32929. },
  32930. enumerable: true,
  32931. configurable: true
  32932. });
  32933. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32934. /**
  32935. * Gets the midtones Exposure value.
  32936. * 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.
  32937. */
  32938. get: function () {
  32939. return this._midtonesExposure;
  32940. },
  32941. /**
  32942. * Sets the midtones Exposure value.
  32943. * 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.
  32944. */
  32945. set: function (value) {
  32946. this._midtonesExposure = value;
  32947. this._dirty = true;
  32948. },
  32949. enumerable: true,
  32950. configurable: true
  32951. });
  32952. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32953. /**
  32954. * Gets the shadows Hue value.
  32955. * 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).
  32956. */
  32957. get: function () {
  32958. return this._shadowsHue;
  32959. },
  32960. /**
  32961. * Sets the shadows Hue value.
  32962. * 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).
  32963. */
  32964. set: function (value) {
  32965. this._shadowsHue = value;
  32966. this._dirty = true;
  32967. },
  32968. enumerable: true,
  32969. configurable: true
  32970. });
  32971. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32972. /**
  32973. * Gets the shadows Density value.
  32974. * 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.
  32975. * Values less than zero provide a filter of opposite hue.
  32976. */
  32977. get: function () {
  32978. return this._shadowsDensity;
  32979. },
  32980. /**
  32981. * Sets the shadows Density value.
  32982. * 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.
  32983. * Values less than zero provide a filter of opposite hue.
  32984. */
  32985. set: function (value) {
  32986. this._shadowsDensity = value;
  32987. this._dirty = true;
  32988. },
  32989. enumerable: true,
  32990. configurable: true
  32991. });
  32992. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32993. /**
  32994. * Gets the shadows Saturation value.
  32995. * 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.
  32996. */
  32997. get: function () {
  32998. return this._shadowsSaturation;
  32999. },
  33000. /**
  33001. * Sets the shadows Saturation value.
  33002. * 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.
  33003. */
  33004. set: function (value) {
  33005. this._shadowsSaturation = value;
  33006. this._dirty = true;
  33007. },
  33008. enumerable: true,
  33009. configurable: true
  33010. });
  33011. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33012. /**
  33013. * Gets the shadows Exposure value.
  33014. * 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.
  33015. */
  33016. get: function () {
  33017. return this._shadowsExposure;
  33018. },
  33019. /**
  33020. * Sets the shadows Exposure value.
  33021. * 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.
  33022. */
  33023. set: function (value) {
  33024. this._shadowsExposure = value;
  33025. this._dirty = true;
  33026. },
  33027. enumerable: true,
  33028. configurable: true
  33029. });
  33030. ColorCurves.prototype.getClassName = function () {
  33031. return "ColorCurves";
  33032. };
  33033. /**
  33034. * Binds the color curves to the shader.
  33035. * @param colorCurves The color curve to bind
  33036. * @param effect The effect to bind to
  33037. */
  33038. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33039. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33040. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33041. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33042. if (colorCurves._dirty) {
  33043. colorCurves._dirty = false;
  33044. // Fill in global info.
  33045. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33046. // Compute highlights info.
  33047. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33048. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33049. // Compute midtones info.
  33050. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33051. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33052. // Compute shadows info.
  33053. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33054. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33055. // Compute deltas (neutral is midtones).
  33056. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33057. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33058. }
  33059. if (effect) {
  33060. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33061. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33062. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33063. }
  33064. };
  33065. /**
  33066. * Prepare the list of uniforms associated with the ColorCurves effects.
  33067. * @param uniformsList The list of uniforms used in the effect
  33068. */
  33069. ColorCurves.PrepareUniforms = function (uniformsList) {
  33070. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33071. };
  33072. /**
  33073. * Returns color grading data based on a hue, density, saturation and exposure value.
  33074. * @param filterHue The hue of the color filter.
  33075. * @param filterDensity The density of the color filter.
  33076. * @param saturation The saturation.
  33077. * @param exposure The exposure.
  33078. * @param result The result data container.
  33079. */
  33080. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33081. if (hue == null) {
  33082. return;
  33083. }
  33084. hue = ColorCurves.clamp(hue, 0, 360);
  33085. density = ColorCurves.clamp(density, -100, 100);
  33086. saturation = ColorCurves.clamp(saturation, -100, 100);
  33087. exposure = ColorCurves.clamp(exposure, -100, 100);
  33088. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33089. // so that the maximum filter density is only 50% control. This provides fine control
  33090. // for small values and reasonable range.
  33091. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33092. density *= 0.5;
  33093. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33094. if (density < 0) {
  33095. density *= -1;
  33096. hue = (hue + 180) % 360;
  33097. }
  33098. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33099. result.scaleToRef(2, result);
  33100. result.a = 1 + 0.01 * saturation;
  33101. };
  33102. /**
  33103. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33104. * @param value The input slider value in range [-100,100].
  33105. * @returns Adjusted value.
  33106. */
  33107. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33108. value /= 100;
  33109. var x = Math.abs(value);
  33110. x = Math.pow(x, 2);
  33111. if (value < 0) {
  33112. x *= -1;
  33113. }
  33114. x *= 100;
  33115. return x;
  33116. };
  33117. /**
  33118. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33119. * @param hue The hue (H) input.
  33120. * @param saturation The saturation (S) input.
  33121. * @param brightness The brightness (B) input.
  33122. * @result An RGBA color represented as Vector4.
  33123. */
  33124. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33125. var h = ColorCurves.clamp(hue, 0, 360);
  33126. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33127. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33128. if (s === 0) {
  33129. result.r = v;
  33130. result.g = v;
  33131. result.b = v;
  33132. }
  33133. else {
  33134. // sector 0 to 5
  33135. h /= 60;
  33136. var i = Math.floor(h);
  33137. // fractional part of h
  33138. var f = h - i;
  33139. var p = v * (1 - s);
  33140. var q = v * (1 - s * f);
  33141. var t = v * (1 - s * (1 - f));
  33142. switch (i) {
  33143. case 0:
  33144. result.r = v;
  33145. result.g = t;
  33146. result.b = p;
  33147. break;
  33148. case 1:
  33149. result.r = q;
  33150. result.g = v;
  33151. result.b = p;
  33152. break;
  33153. case 2:
  33154. result.r = p;
  33155. result.g = v;
  33156. result.b = t;
  33157. break;
  33158. case 3:
  33159. result.r = p;
  33160. result.g = q;
  33161. result.b = v;
  33162. break;
  33163. case 4:
  33164. result.r = t;
  33165. result.g = p;
  33166. result.b = v;
  33167. break;
  33168. default:// case 5:
  33169. result.r = v;
  33170. result.g = p;
  33171. result.b = q;
  33172. break;
  33173. }
  33174. }
  33175. result.a = 1;
  33176. };
  33177. /**
  33178. * Returns a value clamped between min and max
  33179. * @param value The value to clamp
  33180. * @param min The minimum of value
  33181. * @param max The maximum of value
  33182. * @returns The clamped value.
  33183. */
  33184. ColorCurves.clamp = function (value, min, max) {
  33185. return Math.min(Math.max(value, min), max);
  33186. };
  33187. /**
  33188. * Clones the current color curve instance.
  33189. * @return The cloned curves
  33190. */
  33191. ColorCurves.prototype.clone = function () {
  33192. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33193. };
  33194. /**
  33195. * Serializes the current color curve instance to a json representation.
  33196. * @return a JSON representation
  33197. */
  33198. ColorCurves.prototype.serialize = function () {
  33199. return BABYLON.SerializationHelper.Serialize(this);
  33200. };
  33201. /**
  33202. * Parses the color curve from a json representation.
  33203. * @param source the JSON source to parse
  33204. * @return The parsed curves
  33205. */
  33206. ColorCurves.Parse = function (source) {
  33207. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33208. };
  33209. __decorate([
  33210. BABYLON.serialize()
  33211. ], ColorCurves.prototype, "_globalHue", void 0);
  33212. __decorate([
  33213. BABYLON.serialize()
  33214. ], ColorCurves.prototype, "_globalDensity", void 0);
  33215. __decorate([
  33216. BABYLON.serialize()
  33217. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33218. __decorate([
  33219. BABYLON.serialize()
  33220. ], ColorCurves.prototype, "_globalExposure", void 0);
  33221. __decorate([
  33222. BABYLON.serialize()
  33223. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33224. __decorate([
  33225. BABYLON.serialize()
  33226. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33227. __decorate([
  33228. BABYLON.serialize()
  33229. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33230. __decorate([
  33231. BABYLON.serialize()
  33232. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33233. __decorate([
  33234. BABYLON.serialize()
  33235. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33236. __decorate([
  33237. BABYLON.serialize()
  33238. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33239. __decorate([
  33240. BABYLON.serialize()
  33241. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33242. __decorate([
  33243. BABYLON.serialize()
  33244. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33245. return ColorCurves;
  33246. }());
  33247. BABYLON.ColorCurves = ColorCurves;
  33248. })(BABYLON || (BABYLON = {}));
  33249. //# sourceMappingURL=babylon.colorCurves.js.map
  33250. var BABYLON;
  33251. (function (BABYLON) {
  33252. var StandardMaterialDefines = /** @class */ (function (_super) {
  33253. __extends(StandardMaterialDefines, _super);
  33254. function StandardMaterialDefines() {
  33255. var _this = _super.call(this) || this;
  33256. _this.MAINUV1 = false;
  33257. _this.MAINUV2 = false;
  33258. _this.DIFFUSE = false;
  33259. _this.DIFFUSEDIRECTUV = 0;
  33260. _this.AMBIENT = false;
  33261. _this.AMBIENTDIRECTUV = 0;
  33262. _this.OPACITY = false;
  33263. _this.OPACITYDIRECTUV = 0;
  33264. _this.OPACITYRGB = false;
  33265. _this.REFLECTION = false;
  33266. _this.EMISSIVE = false;
  33267. _this.EMISSIVEDIRECTUV = 0;
  33268. _this.SPECULAR = false;
  33269. _this.SPECULARDIRECTUV = 0;
  33270. _this.BUMP = false;
  33271. _this.BUMPDIRECTUV = 0;
  33272. _this.PARALLAX = false;
  33273. _this.PARALLAXOCCLUSION = false;
  33274. _this.SPECULAROVERALPHA = false;
  33275. _this.CLIPPLANE = false;
  33276. _this.ALPHATEST = false;
  33277. _this.DEPTHPREPASS = false;
  33278. _this.ALPHAFROMDIFFUSE = false;
  33279. _this.POINTSIZE = false;
  33280. _this.FOG = false;
  33281. _this.SPECULARTERM = false;
  33282. _this.DIFFUSEFRESNEL = false;
  33283. _this.OPACITYFRESNEL = false;
  33284. _this.REFLECTIONFRESNEL = false;
  33285. _this.REFRACTIONFRESNEL = false;
  33286. _this.EMISSIVEFRESNEL = false;
  33287. _this.FRESNEL = false;
  33288. _this.NORMAL = false;
  33289. _this.UV1 = false;
  33290. _this.UV2 = false;
  33291. _this.VERTEXCOLOR = false;
  33292. _this.VERTEXALPHA = false;
  33293. _this.NUM_BONE_INFLUENCERS = 0;
  33294. _this.BonesPerMesh = 0;
  33295. _this.INSTANCES = false;
  33296. _this.GLOSSINESS = false;
  33297. _this.ROUGHNESS = false;
  33298. _this.EMISSIVEASILLUMINATION = false;
  33299. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33300. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33301. _this.LIGHTMAP = false;
  33302. _this.LIGHTMAPDIRECTUV = 0;
  33303. _this.USELIGHTMAPASSHADOWMAP = false;
  33304. _this.REFLECTIONMAP_3D = false;
  33305. _this.REFLECTIONMAP_SPHERICAL = false;
  33306. _this.REFLECTIONMAP_PLANAR = false;
  33307. _this.REFLECTIONMAP_CUBIC = false;
  33308. _this.REFLECTIONMAP_PROJECTION = false;
  33309. _this.REFLECTIONMAP_SKYBOX = false;
  33310. _this.REFLECTIONMAP_EXPLICIT = false;
  33311. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33312. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33313. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33314. _this.INVERTCUBICMAP = false;
  33315. _this.LOGARITHMICDEPTH = false;
  33316. _this.REFRACTION = false;
  33317. _this.REFRACTIONMAP_3D = false;
  33318. _this.REFLECTIONOVERALPHA = false;
  33319. _this.TWOSIDEDLIGHTING = false;
  33320. _this.SHADOWFLOAT = false;
  33321. _this.MORPHTARGETS = false;
  33322. _this.MORPHTARGETS_NORMAL = false;
  33323. _this.MORPHTARGETS_TANGENT = false;
  33324. _this.NUM_MORPH_INFLUENCERS = 0;
  33325. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33326. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33327. _this.IMAGEPROCESSING = false;
  33328. _this.VIGNETTE = false;
  33329. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33330. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33331. _this.TONEMAPPING = false;
  33332. _this.CONTRAST = false;
  33333. _this.COLORCURVES = false;
  33334. _this.COLORGRADING = false;
  33335. _this.COLORGRADING3D = false;
  33336. _this.SAMPLER3DGREENDEPTH = false;
  33337. _this.SAMPLER3DBGRMAP = false;
  33338. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33339. _this.EXPOSURE = false;
  33340. _this.rebuild();
  33341. return _this;
  33342. }
  33343. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33344. var modes = [
  33345. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33346. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33347. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33348. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33349. ];
  33350. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33351. var mode = modes_1[_i];
  33352. this[mode] = (mode === modeToEnable);
  33353. }
  33354. };
  33355. return StandardMaterialDefines;
  33356. }(BABYLON.MaterialDefines));
  33357. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33358. var StandardMaterial = /** @class */ (function (_super) {
  33359. __extends(StandardMaterial, _super);
  33360. function StandardMaterial(name, scene) {
  33361. var _this = _super.call(this, name, scene) || this;
  33362. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33363. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33364. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33365. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33366. _this.specularPower = 64;
  33367. _this._useAlphaFromDiffuseTexture = false;
  33368. _this._useEmissiveAsIllumination = false;
  33369. _this._linkEmissiveWithDiffuse = false;
  33370. _this._useSpecularOverAlpha = false;
  33371. _this._useReflectionOverAlpha = false;
  33372. _this._disableLighting = false;
  33373. _this._useParallax = false;
  33374. _this._useParallaxOcclusion = false;
  33375. _this.parallaxScaleBias = 0.05;
  33376. _this._roughness = 0;
  33377. _this.indexOfRefraction = 0.98;
  33378. _this.invertRefractionY = true;
  33379. _this._useLightmapAsShadowmap = false;
  33380. _this._useReflectionFresnelFromSpecular = false;
  33381. _this._useGlossinessFromSpecularMapAlpha = false;
  33382. _this._maxSimultaneousLights = 4;
  33383. /**
  33384. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33385. */
  33386. _this._invertNormalMapX = false;
  33387. /**
  33388. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33389. */
  33390. _this._invertNormalMapY = false;
  33391. /**
  33392. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33393. */
  33394. _this._twoSidedLighting = false;
  33395. _this._renderTargets = new BABYLON.SmartArray(16);
  33396. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33397. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33398. // Setup the default processing configuration to the scene.
  33399. _this._attachImageProcessingConfiguration(null);
  33400. _this.getRenderTargetTextures = function () {
  33401. _this._renderTargets.reset();
  33402. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33403. _this._renderTargets.push(_this._reflectionTexture);
  33404. }
  33405. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33406. _this._renderTargets.push(_this._refractionTexture);
  33407. }
  33408. return _this._renderTargets;
  33409. };
  33410. return _this;
  33411. }
  33412. ;
  33413. ;
  33414. ;
  33415. ;
  33416. ;
  33417. ;
  33418. ;
  33419. ;
  33420. ;
  33421. ;
  33422. ;
  33423. ;
  33424. ;
  33425. ;
  33426. ;
  33427. ;
  33428. ;
  33429. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33430. /**
  33431. * Gets the image processing configuration used either in this material.
  33432. */
  33433. get: function () {
  33434. return this._imageProcessingConfiguration;
  33435. },
  33436. /**
  33437. * Sets the Default image processing configuration used either in the this material.
  33438. *
  33439. * If sets to null, the scene one is in use.
  33440. */
  33441. set: function (value) {
  33442. this._attachImageProcessingConfiguration(value);
  33443. // Ensure the effect will be rebuilt.
  33444. this._markAllSubMeshesAsTexturesDirty();
  33445. },
  33446. enumerable: true,
  33447. configurable: true
  33448. });
  33449. /**
  33450. * Attaches a new image processing configuration to the Standard Material.
  33451. * @param configuration
  33452. */
  33453. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33454. var _this = this;
  33455. if (configuration === this._imageProcessingConfiguration) {
  33456. return;
  33457. }
  33458. // Detaches observer.
  33459. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33460. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33461. }
  33462. // Pick the scene configuration if needed.
  33463. if (!configuration) {
  33464. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33465. }
  33466. else {
  33467. this._imageProcessingConfiguration = configuration;
  33468. }
  33469. // Attaches observer.
  33470. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33471. _this._markAllSubMeshesAsImageProcessingDirty();
  33472. });
  33473. };
  33474. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33475. /**
  33476. * Gets wether the color curves effect is enabled.
  33477. */
  33478. get: function () {
  33479. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33480. },
  33481. /**
  33482. * Sets wether the color curves effect is enabled.
  33483. */
  33484. set: function (value) {
  33485. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33486. },
  33487. enumerable: true,
  33488. configurable: true
  33489. });
  33490. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33491. /**
  33492. * Gets wether the color grading effect is enabled.
  33493. */
  33494. get: function () {
  33495. return this.imageProcessingConfiguration.colorGradingEnabled;
  33496. },
  33497. /**
  33498. * Gets wether the color grading effect is enabled.
  33499. */
  33500. set: function (value) {
  33501. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33502. },
  33503. enumerable: true,
  33504. configurable: true
  33505. });
  33506. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33507. /**
  33508. * Gets wether tonemapping is enabled or not.
  33509. */
  33510. get: function () {
  33511. return this._imageProcessingConfiguration.toneMappingEnabled;
  33512. },
  33513. /**
  33514. * Sets wether tonemapping is enabled or not
  33515. */
  33516. set: function (value) {
  33517. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33518. },
  33519. enumerable: true,
  33520. configurable: true
  33521. });
  33522. ;
  33523. ;
  33524. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33525. /**
  33526. * The camera exposure used on this material.
  33527. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33528. * This corresponds to a photographic exposure.
  33529. */
  33530. get: function () {
  33531. return this._imageProcessingConfiguration.exposure;
  33532. },
  33533. /**
  33534. * The camera exposure used on this material.
  33535. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33536. * This corresponds to a photographic exposure.
  33537. */
  33538. set: function (value) {
  33539. this._imageProcessingConfiguration.exposure = value;
  33540. },
  33541. enumerable: true,
  33542. configurable: true
  33543. });
  33544. ;
  33545. ;
  33546. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33547. /**
  33548. * Gets The camera contrast used on this material.
  33549. */
  33550. get: function () {
  33551. return this._imageProcessingConfiguration.contrast;
  33552. },
  33553. /**
  33554. * Sets The camera contrast used on this material.
  33555. */
  33556. set: function (value) {
  33557. this._imageProcessingConfiguration.contrast = value;
  33558. },
  33559. enumerable: true,
  33560. configurable: true
  33561. });
  33562. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33563. /**
  33564. * Gets the Color Grading 2D Lookup Texture.
  33565. */
  33566. get: function () {
  33567. return this._imageProcessingConfiguration.colorGradingTexture;
  33568. },
  33569. /**
  33570. * Sets the Color Grading 2D Lookup Texture.
  33571. */
  33572. set: function (value) {
  33573. this._imageProcessingConfiguration.colorGradingTexture = value;
  33574. },
  33575. enumerable: true,
  33576. configurable: true
  33577. });
  33578. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33579. /**
  33580. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33581. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33582. * 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;
  33583. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33584. */
  33585. get: function () {
  33586. return this._imageProcessingConfiguration.colorCurves;
  33587. },
  33588. /**
  33589. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33590. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33591. * 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;
  33592. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33593. */
  33594. set: function (value) {
  33595. this._imageProcessingConfiguration.colorCurves = value;
  33596. },
  33597. enumerable: true,
  33598. configurable: true
  33599. });
  33600. StandardMaterial.prototype.getClassName = function () {
  33601. return "StandardMaterial";
  33602. };
  33603. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33604. get: function () {
  33605. return this._useLogarithmicDepth;
  33606. },
  33607. set: function (value) {
  33608. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33609. this._markAllSubMeshesAsMiscDirty();
  33610. },
  33611. enumerable: true,
  33612. configurable: true
  33613. });
  33614. StandardMaterial.prototype.needAlphaBlending = function () {
  33615. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33616. };
  33617. StandardMaterial.prototype.needAlphaTesting = function () {
  33618. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33619. };
  33620. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33621. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33622. };
  33623. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33624. return this._diffuseTexture;
  33625. };
  33626. /**
  33627. * Child classes can use it to update shaders
  33628. */
  33629. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33630. if (useInstances === void 0) { useInstances = false; }
  33631. if (subMesh.effect && this.isFrozen) {
  33632. if (this._wasPreviouslyReady && subMesh.effect) {
  33633. return true;
  33634. }
  33635. }
  33636. if (!subMesh._materialDefines) {
  33637. subMesh._materialDefines = new StandardMaterialDefines();
  33638. }
  33639. var scene = this.getScene();
  33640. var defines = subMesh._materialDefines;
  33641. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33642. if (defines._renderId === scene.getRenderId()) {
  33643. return true;
  33644. }
  33645. }
  33646. var engine = scene.getEngine();
  33647. // Lights
  33648. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33649. // Textures
  33650. if (defines._areTexturesDirty) {
  33651. defines._needUVs = false;
  33652. defines.MAINUV1 = false;
  33653. defines.MAINUV2 = false;
  33654. if (scene.texturesEnabled) {
  33655. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33656. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33657. return false;
  33658. }
  33659. else {
  33660. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33661. }
  33662. }
  33663. else {
  33664. defines.DIFFUSE = false;
  33665. }
  33666. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33667. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33668. return false;
  33669. }
  33670. else {
  33671. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33672. }
  33673. }
  33674. else {
  33675. defines.AMBIENT = false;
  33676. }
  33677. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33678. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33679. return false;
  33680. }
  33681. else {
  33682. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33683. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33684. }
  33685. }
  33686. else {
  33687. defines.OPACITY = false;
  33688. }
  33689. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33690. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33691. return false;
  33692. }
  33693. else {
  33694. defines._needNormals = true;
  33695. defines.REFLECTION = true;
  33696. defines.ROUGHNESS = (this._roughness > 0);
  33697. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33698. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33699. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33700. switch (this._reflectionTexture.coordinatesMode) {
  33701. case BABYLON.Texture.CUBIC_MODE:
  33702. case BABYLON.Texture.INVCUBIC_MODE:
  33703. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33704. break;
  33705. case BABYLON.Texture.EXPLICIT_MODE:
  33706. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33707. break;
  33708. case BABYLON.Texture.PLANAR_MODE:
  33709. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33710. break;
  33711. case BABYLON.Texture.PROJECTION_MODE:
  33712. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33713. break;
  33714. case BABYLON.Texture.SKYBOX_MODE:
  33715. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33716. break;
  33717. case BABYLON.Texture.SPHERICAL_MODE:
  33718. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33719. break;
  33720. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33721. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33722. break;
  33723. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33724. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33725. break;
  33726. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33727. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33728. break;
  33729. }
  33730. }
  33731. }
  33732. else {
  33733. defines.REFLECTION = false;
  33734. }
  33735. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33736. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33737. return false;
  33738. }
  33739. else {
  33740. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33741. }
  33742. }
  33743. else {
  33744. defines.EMISSIVE = false;
  33745. }
  33746. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33747. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33748. return false;
  33749. }
  33750. else {
  33751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33752. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33753. }
  33754. }
  33755. else {
  33756. defines.LIGHTMAP = false;
  33757. }
  33758. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33759. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33760. return false;
  33761. }
  33762. else {
  33763. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33764. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33765. }
  33766. }
  33767. else {
  33768. defines.SPECULAR = false;
  33769. }
  33770. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33771. // Bump texure can not be not blocking.
  33772. if (!this._bumpTexture.isReady()) {
  33773. return false;
  33774. }
  33775. else {
  33776. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33777. defines.PARALLAX = this._useParallax;
  33778. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33779. }
  33780. }
  33781. else {
  33782. defines.BUMP = false;
  33783. }
  33784. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33785. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33786. return false;
  33787. }
  33788. else {
  33789. defines._needUVs = true;
  33790. defines.REFRACTION = true;
  33791. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33792. }
  33793. }
  33794. else {
  33795. defines.REFRACTION = false;
  33796. }
  33797. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33798. }
  33799. else {
  33800. defines.DIFFUSE = false;
  33801. defines.AMBIENT = false;
  33802. defines.OPACITY = false;
  33803. defines.REFLECTION = false;
  33804. defines.EMISSIVE = false;
  33805. defines.LIGHTMAP = false;
  33806. defines.BUMP = false;
  33807. defines.REFRACTION = false;
  33808. }
  33809. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33810. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33811. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33812. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33813. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33814. }
  33815. if (defines._areImageProcessingDirty) {
  33816. if (!this._imageProcessingConfiguration.isReady()) {
  33817. return false;
  33818. }
  33819. this._imageProcessingConfiguration.prepareDefines(defines);
  33820. }
  33821. if (defines._areFresnelDirty) {
  33822. if (StandardMaterial.FresnelEnabled) {
  33823. // Fresnel
  33824. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33825. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33826. this._reflectionFresnelParameters) {
  33827. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33828. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33829. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33830. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33831. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33832. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33833. defines._needNormals = true;
  33834. defines.FRESNEL = true;
  33835. }
  33836. }
  33837. else {
  33838. defines.FRESNEL = false;
  33839. }
  33840. }
  33841. // Misc.
  33842. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33843. // Attribs
  33844. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33845. // Values that need to be evaluated on every frame
  33846. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33847. // Get correct effect
  33848. if (defines.isDirty) {
  33849. defines.markAsProcessed();
  33850. scene.resetCachedMaterial();
  33851. // Fallbacks
  33852. var fallbacks = new BABYLON.EffectFallbacks();
  33853. if (defines.REFLECTION) {
  33854. fallbacks.addFallback(0, "REFLECTION");
  33855. }
  33856. if (defines.SPECULAR) {
  33857. fallbacks.addFallback(0, "SPECULAR");
  33858. }
  33859. if (defines.BUMP) {
  33860. fallbacks.addFallback(0, "BUMP");
  33861. }
  33862. if (defines.PARALLAX) {
  33863. fallbacks.addFallback(1, "PARALLAX");
  33864. }
  33865. if (defines.PARALLAXOCCLUSION) {
  33866. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33867. }
  33868. if (defines.SPECULAROVERALPHA) {
  33869. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33870. }
  33871. if (defines.FOG) {
  33872. fallbacks.addFallback(1, "FOG");
  33873. }
  33874. if (defines.POINTSIZE) {
  33875. fallbacks.addFallback(0, "POINTSIZE");
  33876. }
  33877. if (defines.LOGARITHMICDEPTH) {
  33878. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33879. }
  33880. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33881. if (defines.SPECULARTERM) {
  33882. fallbacks.addFallback(0, "SPECULARTERM");
  33883. }
  33884. if (defines.DIFFUSEFRESNEL) {
  33885. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33886. }
  33887. if (defines.OPACITYFRESNEL) {
  33888. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33889. }
  33890. if (defines.REFLECTIONFRESNEL) {
  33891. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33892. }
  33893. if (defines.EMISSIVEFRESNEL) {
  33894. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33895. }
  33896. if (defines.FRESNEL) {
  33897. fallbacks.addFallback(4, "FRESNEL");
  33898. }
  33899. //Attributes
  33900. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33901. if (defines.NORMAL) {
  33902. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33903. }
  33904. if (defines.UV1) {
  33905. attribs.push(BABYLON.VertexBuffer.UVKind);
  33906. }
  33907. if (defines.UV2) {
  33908. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33909. }
  33910. if (defines.VERTEXCOLOR) {
  33911. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33912. }
  33913. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33914. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33915. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33916. var shaderName = "default";
  33917. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33918. "vFogInfos", "vFogColor", "pointSize",
  33919. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33920. "mBones",
  33921. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33922. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33923. "logarithmicDepthConstant", "vTangentSpaceParams"
  33924. ];
  33925. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33926. var uniformBuffers = ["Material", "Scene"];
  33927. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33928. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33929. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33930. uniformsNames: uniforms,
  33931. uniformBuffersNames: uniformBuffers,
  33932. samplers: samplers,
  33933. defines: defines,
  33934. maxSimultaneousLights: this._maxSimultaneousLights
  33935. });
  33936. if (this.customShaderNameResolve) {
  33937. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33938. }
  33939. var join = defines.toString();
  33940. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33941. attributes: attribs,
  33942. uniformsNames: uniforms,
  33943. uniformBuffersNames: uniformBuffers,
  33944. samplers: samplers,
  33945. defines: join,
  33946. fallbacks: fallbacks,
  33947. onCompiled: this.onCompiled,
  33948. onError: this.onError,
  33949. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33950. }, engine), defines);
  33951. this.buildUniformLayout();
  33952. }
  33953. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33954. return false;
  33955. }
  33956. defines._renderId = scene.getRenderId();
  33957. this._wasPreviouslyReady = true;
  33958. return true;
  33959. };
  33960. StandardMaterial.prototype.buildUniformLayout = function () {
  33961. // Order is important !
  33962. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33963. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33964. this._uniformBuffer.addUniform("opacityParts", 4);
  33965. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33966. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33967. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33968. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33969. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33970. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33971. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33972. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33973. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33974. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33975. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33976. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33977. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33978. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33979. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33980. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33981. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33982. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33983. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33984. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33985. this._uniformBuffer.addUniform("specularMatrix", 16);
  33986. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33987. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33988. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33989. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33990. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33991. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33992. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33993. this._uniformBuffer.addUniform("pointSize", 1);
  33994. this._uniformBuffer.create();
  33995. };
  33996. StandardMaterial.prototype.unbind = function () {
  33997. if (this._activeEffect) {
  33998. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33999. this._activeEffect.setTexture("reflection2DSampler", null);
  34000. }
  34001. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34002. this._activeEffect.setTexture("refraction2DSampler", null);
  34003. }
  34004. }
  34005. _super.prototype.unbind.call(this);
  34006. };
  34007. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34008. var scene = this.getScene();
  34009. var defines = subMesh._materialDefines;
  34010. if (!defines) {
  34011. return;
  34012. }
  34013. var effect = subMesh.effect;
  34014. if (!effect) {
  34015. return;
  34016. }
  34017. this._activeEffect = effect;
  34018. // Matrices
  34019. this.bindOnlyWorldMatrix(world);
  34020. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34021. // Bones
  34022. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34023. if (mustRebind) {
  34024. this._uniformBuffer.bindToEffect(effect, "Material");
  34025. this.bindViewProjection(effect);
  34026. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34027. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34028. // Fresnel
  34029. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34030. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34031. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34032. }
  34033. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34034. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34035. }
  34036. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34037. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34038. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34039. }
  34040. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34041. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34042. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34043. }
  34044. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34045. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34046. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34047. }
  34048. }
  34049. // Textures
  34050. if (scene.texturesEnabled) {
  34051. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34052. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34053. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34054. }
  34055. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34056. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34057. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34058. }
  34059. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34060. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34061. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34062. }
  34063. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34064. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34065. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34066. }
  34067. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34068. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34069. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34070. }
  34071. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34072. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34073. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34074. }
  34075. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34076. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34077. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34078. }
  34079. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34080. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34081. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34082. if (scene._mirroredCameraPosition) {
  34083. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34084. }
  34085. else {
  34086. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34087. }
  34088. }
  34089. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34090. var depth = 1.0;
  34091. if (!this._refractionTexture.isCube) {
  34092. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34093. if (this._refractionTexture.depth) {
  34094. depth = this._refractionTexture.depth;
  34095. }
  34096. }
  34097. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34098. }
  34099. }
  34100. // Point size
  34101. if (this.pointsCloud) {
  34102. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34103. }
  34104. if (defines.SPECULARTERM) {
  34105. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34106. }
  34107. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34108. // Diffuse
  34109. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34110. }
  34111. // Textures
  34112. if (scene.texturesEnabled) {
  34113. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34114. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34115. }
  34116. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34117. effect.setTexture("ambientSampler", this._ambientTexture);
  34118. }
  34119. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34120. effect.setTexture("opacitySampler", this._opacityTexture);
  34121. }
  34122. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34123. if (this._reflectionTexture.isCube) {
  34124. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34125. }
  34126. else {
  34127. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34128. }
  34129. }
  34130. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34131. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34132. }
  34133. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34134. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34135. }
  34136. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34137. effect.setTexture("specularSampler", this._specularTexture);
  34138. }
  34139. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34140. effect.setTexture("bumpSampler", this._bumpTexture);
  34141. }
  34142. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34143. var depth = 1.0;
  34144. if (this._refractionTexture.isCube) {
  34145. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34146. }
  34147. else {
  34148. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34149. }
  34150. }
  34151. }
  34152. // Clip plane
  34153. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34154. // Colors
  34155. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34156. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34157. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34158. }
  34159. if (mustRebind || !this.isFrozen) {
  34160. // Lights
  34161. if (scene.lightsEnabled && !this._disableLighting) {
  34162. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34163. }
  34164. // View
  34165. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34166. this.bindView(effect);
  34167. }
  34168. // Fog
  34169. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34170. // Morph targets
  34171. if (defines.NUM_MORPH_INFLUENCERS) {
  34172. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34173. }
  34174. // Log. depth
  34175. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34176. // image processing
  34177. this._imageProcessingConfiguration.bind(this._activeEffect);
  34178. }
  34179. this._uniformBuffer.update();
  34180. this._afterBind(mesh, this._activeEffect);
  34181. };
  34182. StandardMaterial.prototype.getAnimatables = function () {
  34183. var results = [];
  34184. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34185. results.push(this._diffuseTexture);
  34186. }
  34187. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34188. results.push(this._ambientTexture);
  34189. }
  34190. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34191. results.push(this._opacityTexture);
  34192. }
  34193. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34194. results.push(this._reflectionTexture);
  34195. }
  34196. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34197. results.push(this._emissiveTexture);
  34198. }
  34199. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34200. results.push(this._specularTexture);
  34201. }
  34202. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34203. results.push(this._bumpTexture);
  34204. }
  34205. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34206. results.push(this._lightmapTexture);
  34207. }
  34208. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34209. results.push(this._refractionTexture);
  34210. }
  34211. return results;
  34212. };
  34213. StandardMaterial.prototype.getActiveTextures = function () {
  34214. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34215. if (this._diffuseTexture) {
  34216. activeTextures.push(this._diffuseTexture);
  34217. }
  34218. if (this._ambientTexture) {
  34219. activeTextures.push(this._ambientTexture);
  34220. }
  34221. if (this._opacityTexture) {
  34222. activeTextures.push(this._opacityTexture);
  34223. }
  34224. if (this._reflectionTexture) {
  34225. activeTextures.push(this._reflectionTexture);
  34226. }
  34227. if (this._emissiveTexture) {
  34228. activeTextures.push(this._emissiveTexture);
  34229. }
  34230. if (this._specularTexture) {
  34231. activeTextures.push(this._specularTexture);
  34232. }
  34233. if (this._bumpTexture) {
  34234. activeTextures.push(this._bumpTexture);
  34235. }
  34236. if (this._lightmapTexture) {
  34237. activeTextures.push(this._lightmapTexture);
  34238. }
  34239. if (this._refractionTexture) {
  34240. activeTextures.push(this._refractionTexture);
  34241. }
  34242. return activeTextures;
  34243. };
  34244. StandardMaterial.prototype.hasTexture = function (texture) {
  34245. if (_super.prototype.hasTexture.call(this, texture)) {
  34246. return true;
  34247. }
  34248. if (this._diffuseTexture === texture) {
  34249. return true;
  34250. }
  34251. if (this._ambientTexture === texture) {
  34252. return true;
  34253. }
  34254. if (this._opacityTexture === texture) {
  34255. return true;
  34256. }
  34257. if (this._reflectionTexture === texture) {
  34258. return true;
  34259. }
  34260. if (this._emissiveTexture === texture) {
  34261. return true;
  34262. }
  34263. if (this._specularTexture === texture) {
  34264. return true;
  34265. }
  34266. if (this._bumpTexture === texture) {
  34267. return true;
  34268. }
  34269. if (this._lightmapTexture === texture) {
  34270. return true;
  34271. }
  34272. if (this._refractionTexture === texture) {
  34273. return true;
  34274. }
  34275. return false;
  34276. };
  34277. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34278. if (forceDisposeTextures) {
  34279. if (this._diffuseTexture) {
  34280. this._diffuseTexture.dispose();
  34281. }
  34282. if (this._ambientTexture) {
  34283. this._ambientTexture.dispose();
  34284. }
  34285. if (this._opacityTexture) {
  34286. this._opacityTexture.dispose();
  34287. }
  34288. if (this._reflectionTexture) {
  34289. this._reflectionTexture.dispose();
  34290. }
  34291. if (this._emissiveTexture) {
  34292. this._emissiveTexture.dispose();
  34293. }
  34294. if (this._specularTexture) {
  34295. this._specularTexture.dispose();
  34296. }
  34297. if (this._bumpTexture) {
  34298. this._bumpTexture.dispose();
  34299. }
  34300. if (this._lightmapTexture) {
  34301. this._lightmapTexture.dispose();
  34302. }
  34303. if (this._refractionTexture) {
  34304. this._refractionTexture.dispose();
  34305. }
  34306. }
  34307. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34308. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34309. }
  34310. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34311. };
  34312. StandardMaterial.prototype.clone = function (name) {
  34313. var _this = this;
  34314. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34315. result.name = name;
  34316. result.id = name;
  34317. return result;
  34318. };
  34319. StandardMaterial.prototype.serialize = function () {
  34320. return BABYLON.SerializationHelper.Serialize(this);
  34321. };
  34322. // Statics
  34323. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34324. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34325. };
  34326. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34327. get: function () {
  34328. return StandardMaterial._DiffuseTextureEnabled;
  34329. },
  34330. set: function (value) {
  34331. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34332. return;
  34333. }
  34334. StandardMaterial._DiffuseTextureEnabled = value;
  34335. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34336. },
  34337. enumerable: true,
  34338. configurable: true
  34339. });
  34340. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34341. get: function () {
  34342. return StandardMaterial._AmbientTextureEnabled;
  34343. },
  34344. set: function (value) {
  34345. if (StandardMaterial._AmbientTextureEnabled === value) {
  34346. return;
  34347. }
  34348. StandardMaterial._AmbientTextureEnabled = value;
  34349. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34350. },
  34351. enumerable: true,
  34352. configurable: true
  34353. });
  34354. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34355. get: function () {
  34356. return StandardMaterial._OpacityTextureEnabled;
  34357. },
  34358. set: function (value) {
  34359. if (StandardMaterial._OpacityTextureEnabled === value) {
  34360. return;
  34361. }
  34362. StandardMaterial._OpacityTextureEnabled = value;
  34363. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34364. },
  34365. enumerable: true,
  34366. configurable: true
  34367. });
  34368. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34369. get: function () {
  34370. return StandardMaterial._ReflectionTextureEnabled;
  34371. },
  34372. set: function (value) {
  34373. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34374. return;
  34375. }
  34376. StandardMaterial._ReflectionTextureEnabled = value;
  34377. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34378. },
  34379. enumerable: true,
  34380. configurable: true
  34381. });
  34382. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34383. get: function () {
  34384. return StandardMaterial._EmissiveTextureEnabled;
  34385. },
  34386. set: function (value) {
  34387. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34388. return;
  34389. }
  34390. StandardMaterial._EmissiveTextureEnabled = value;
  34391. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34392. },
  34393. enumerable: true,
  34394. configurable: true
  34395. });
  34396. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34397. get: function () {
  34398. return StandardMaterial._SpecularTextureEnabled;
  34399. },
  34400. set: function (value) {
  34401. if (StandardMaterial._SpecularTextureEnabled === value) {
  34402. return;
  34403. }
  34404. StandardMaterial._SpecularTextureEnabled = value;
  34405. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34406. },
  34407. enumerable: true,
  34408. configurable: true
  34409. });
  34410. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34411. get: function () {
  34412. return StandardMaterial._BumpTextureEnabled;
  34413. },
  34414. set: function (value) {
  34415. if (StandardMaterial._BumpTextureEnabled === value) {
  34416. return;
  34417. }
  34418. StandardMaterial._BumpTextureEnabled = value;
  34419. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34420. },
  34421. enumerable: true,
  34422. configurable: true
  34423. });
  34424. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34425. get: function () {
  34426. return StandardMaterial._LightmapTextureEnabled;
  34427. },
  34428. set: function (value) {
  34429. if (StandardMaterial._LightmapTextureEnabled === value) {
  34430. return;
  34431. }
  34432. StandardMaterial._LightmapTextureEnabled = value;
  34433. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34434. },
  34435. enumerable: true,
  34436. configurable: true
  34437. });
  34438. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34439. get: function () {
  34440. return StandardMaterial._RefractionTextureEnabled;
  34441. },
  34442. set: function (value) {
  34443. if (StandardMaterial._RefractionTextureEnabled === value) {
  34444. return;
  34445. }
  34446. StandardMaterial._RefractionTextureEnabled = value;
  34447. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34448. },
  34449. enumerable: true,
  34450. configurable: true
  34451. });
  34452. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34453. get: function () {
  34454. return StandardMaterial._ColorGradingTextureEnabled;
  34455. },
  34456. set: function (value) {
  34457. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34458. return;
  34459. }
  34460. StandardMaterial._ColorGradingTextureEnabled = value;
  34461. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34462. },
  34463. enumerable: true,
  34464. configurable: true
  34465. });
  34466. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34467. get: function () {
  34468. return StandardMaterial._FresnelEnabled;
  34469. },
  34470. set: function (value) {
  34471. if (StandardMaterial._FresnelEnabled === value) {
  34472. return;
  34473. }
  34474. StandardMaterial._FresnelEnabled = value;
  34475. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34476. },
  34477. enumerable: true,
  34478. configurable: true
  34479. });
  34480. // Flags used to enable or disable a type of texture for all Standard Materials
  34481. StandardMaterial._DiffuseTextureEnabled = true;
  34482. StandardMaterial._AmbientTextureEnabled = true;
  34483. StandardMaterial._OpacityTextureEnabled = true;
  34484. StandardMaterial._ReflectionTextureEnabled = true;
  34485. StandardMaterial._EmissiveTextureEnabled = true;
  34486. StandardMaterial._SpecularTextureEnabled = true;
  34487. StandardMaterial._BumpTextureEnabled = true;
  34488. StandardMaterial._LightmapTextureEnabled = true;
  34489. StandardMaterial._RefractionTextureEnabled = true;
  34490. StandardMaterial._ColorGradingTextureEnabled = true;
  34491. StandardMaterial._FresnelEnabled = true;
  34492. __decorate([
  34493. BABYLON.serializeAsTexture("diffuseTexture")
  34494. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34495. __decorate([
  34496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34497. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34498. __decorate([
  34499. BABYLON.serializeAsTexture("ambientTexture")
  34500. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34501. __decorate([
  34502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34503. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34504. __decorate([
  34505. BABYLON.serializeAsTexture("opacityTexture")
  34506. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34507. __decorate([
  34508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34509. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34510. __decorate([
  34511. BABYLON.serializeAsTexture("reflectionTexture")
  34512. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34513. __decorate([
  34514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34515. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34516. __decorate([
  34517. BABYLON.serializeAsTexture("emissiveTexture")
  34518. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34519. __decorate([
  34520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34521. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34522. __decorate([
  34523. BABYLON.serializeAsTexture("specularTexture")
  34524. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34525. __decorate([
  34526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34527. ], StandardMaterial.prototype, "specularTexture", void 0);
  34528. __decorate([
  34529. BABYLON.serializeAsTexture("bumpTexture")
  34530. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34531. __decorate([
  34532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34533. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34534. __decorate([
  34535. BABYLON.serializeAsTexture("lightmapTexture")
  34536. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34537. __decorate([
  34538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34539. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34540. __decorate([
  34541. BABYLON.serializeAsTexture("refractionTexture")
  34542. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34543. __decorate([
  34544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34545. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34546. __decorate([
  34547. BABYLON.serializeAsColor3("ambient")
  34548. ], StandardMaterial.prototype, "ambientColor", void 0);
  34549. __decorate([
  34550. BABYLON.serializeAsColor3("diffuse")
  34551. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34552. __decorate([
  34553. BABYLON.serializeAsColor3("specular")
  34554. ], StandardMaterial.prototype, "specularColor", void 0);
  34555. __decorate([
  34556. BABYLON.serializeAsColor3("emissive")
  34557. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34558. __decorate([
  34559. BABYLON.serialize()
  34560. ], StandardMaterial.prototype, "specularPower", void 0);
  34561. __decorate([
  34562. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34563. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34564. __decorate([
  34565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34566. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34567. __decorate([
  34568. BABYLON.serialize("useEmissiveAsIllumination")
  34569. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34570. __decorate([
  34571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34572. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34573. __decorate([
  34574. BABYLON.serialize("linkEmissiveWithDiffuse")
  34575. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34576. __decorate([
  34577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34578. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34579. __decorate([
  34580. BABYLON.serialize("useSpecularOverAlpha")
  34581. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34582. __decorate([
  34583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34584. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34585. __decorate([
  34586. BABYLON.serialize("useReflectionOverAlpha")
  34587. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34588. __decorate([
  34589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34590. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34591. __decorate([
  34592. BABYLON.serialize("disableLighting")
  34593. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34594. __decorate([
  34595. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34596. ], StandardMaterial.prototype, "disableLighting", void 0);
  34597. __decorate([
  34598. BABYLON.serialize("useParallax")
  34599. ], StandardMaterial.prototype, "_useParallax", void 0);
  34600. __decorate([
  34601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34602. ], StandardMaterial.prototype, "useParallax", void 0);
  34603. __decorate([
  34604. BABYLON.serialize("useParallaxOcclusion")
  34605. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34606. __decorate([
  34607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34608. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34609. __decorate([
  34610. BABYLON.serialize()
  34611. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34612. __decorate([
  34613. BABYLON.serialize("roughness")
  34614. ], StandardMaterial.prototype, "_roughness", void 0);
  34615. __decorate([
  34616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34617. ], StandardMaterial.prototype, "roughness", void 0);
  34618. __decorate([
  34619. BABYLON.serialize()
  34620. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34621. __decorate([
  34622. BABYLON.serialize()
  34623. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34624. __decorate([
  34625. BABYLON.serialize("useLightmapAsShadowmap")
  34626. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34627. __decorate([
  34628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34629. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34630. __decorate([
  34631. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34632. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34633. __decorate([
  34634. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34635. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34636. __decorate([
  34637. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34638. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34639. __decorate([
  34640. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34641. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34642. __decorate([
  34643. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34644. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34645. __decorate([
  34646. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34647. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34648. __decorate([
  34649. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34650. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34651. __decorate([
  34652. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34653. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34654. __decorate([
  34655. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34656. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34657. __decorate([
  34658. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34659. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34660. __decorate([
  34661. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34662. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34663. __decorate([
  34664. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34665. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34666. __decorate([
  34667. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34668. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34669. __decorate([
  34670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34671. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34672. __decorate([
  34673. BABYLON.serialize("maxSimultaneousLights")
  34674. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34675. __decorate([
  34676. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34677. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34678. __decorate([
  34679. BABYLON.serialize("invertNormalMapX")
  34680. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34681. __decorate([
  34682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34683. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34684. __decorate([
  34685. BABYLON.serialize("invertNormalMapY")
  34686. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34687. __decorate([
  34688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34689. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34690. __decorate([
  34691. BABYLON.serialize("twoSidedLighting")
  34692. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34693. __decorate([
  34694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34695. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34696. __decorate([
  34697. BABYLON.serialize()
  34698. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34699. return StandardMaterial;
  34700. }(BABYLON.PushMaterial));
  34701. BABYLON.StandardMaterial = StandardMaterial;
  34702. })(BABYLON || (BABYLON = {}));
  34703. //# sourceMappingURL=babylon.standardMaterial.js.map
  34704. var BABYLON;
  34705. (function (BABYLON) {
  34706. var PBRMaterialDefines = /** @class */ (function (_super) {
  34707. __extends(PBRMaterialDefines, _super);
  34708. function PBRMaterialDefines() {
  34709. var _this = _super.call(this) || this;
  34710. _this.PBR = true;
  34711. _this.MAINUV1 = false;
  34712. _this.MAINUV2 = false;
  34713. _this.UV1 = false;
  34714. _this.UV2 = false;
  34715. _this.ALBEDO = false;
  34716. _this.ALBEDODIRECTUV = 0;
  34717. _this.VERTEXCOLOR = false;
  34718. _this.AMBIENT = false;
  34719. _this.AMBIENTDIRECTUV = 0;
  34720. _this.AMBIENTINGRAYSCALE = false;
  34721. _this.OPACITY = false;
  34722. _this.VERTEXALPHA = false;
  34723. _this.OPACITYDIRECTUV = 0;
  34724. _this.OPACITYRGB = false;
  34725. _this.ALPHATEST = false;
  34726. _this.DEPTHPREPASS = false;
  34727. _this.ALPHABLEND = false;
  34728. _this.ALPHAFROMALBEDO = false;
  34729. _this.ALPHATESTVALUE = 0.5;
  34730. _this.SPECULAROVERALPHA = false;
  34731. _this.RADIANCEOVERALPHA = false;
  34732. _this.ALPHAFRESNEL = false;
  34733. _this.PREMULTIPLYALPHA = false;
  34734. _this.EMISSIVE = false;
  34735. _this.EMISSIVEDIRECTUV = 0;
  34736. _this.REFLECTIVITY = false;
  34737. _this.REFLECTIVITYDIRECTUV = 0;
  34738. _this.SPECULARTERM = false;
  34739. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34740. _this.MICROSURFACEAUTOMATIC = false;
  34741. _this.LODBASEDMICROSFURACE = false;
  34742. _this.MICROSURFACEMAP = false;
  34743. _this.MICROSURFACEMAPDIRECTUV = 0;
  34744. _this.METALLICWORKFLOW = false;
  34745. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34746. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34747. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34748. _this.AOSTOREINMETALMAPRED = false;
  34749. _this.ENVIRONMENTBRDF = false;
  34750. _this.NORMAL = false;
  34751. _this.TANGENT = false;
  34752. _this.BUMP = false;
  34753. _this.BUMPDIRECTUV = 0;
  34754. _this.PARALLAX = false;
  34755. _this.PARALLAXOCCLUSION = false;
  34756. _this.NORMALXYSCALE = true;
  34757. _this.LIGHTMAP = false;
  34758. _this.LIGHTMAPDIRECTUV = 0;
  34759. _this.USELIGHTMAPASSHADOWMAP = false;
  34760. _this.REFLECTION = false;
  34761. _this.REFLECTIONMAP_3D = false;
  34762. _this.REFLECTIONMAP_SPHERICAL = false;
  34763. _this.REFLECTIONMAP_PLANAR = false;
  34764. _this.REFLECTIONMAP_CUBIC = false;
  34765. _this.REFLECTIONMAP_PROJECTION = false;
  34766. _this.REFLECTIONMAP_SKYBOX = false;
  34767. _this.REFLECTIONMAP_EXPLICIT = false;
  34768. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34769. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34770. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34771. _this.INVERTCUBICMAP = false;
  34772. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34773. _this.USESPHERICALINVERTEX = false;
  34774. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34775. _this.LODINREFLECTIONALPHA = false;
  34776. _this.GAMMAREFLECTION = false;
  34777. _this.REFRACTION = false;
  34778. _this.REFRACTIONMAP_3D = false;
  34779. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34780. _this.LODINREFRACTIONALPHA = false;
  34781. _this.GAMMAREFRACTION = false;
  34782. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34783. _this.INSTANCES = false;
  34784. _this.NUM_BONE_INFLUENCERS = 0;
  34785. _this.BonesPerMesh = 0;
  34786. _this.NONUNIFORMSCALING = false;
  34787. _this.MORPHTARGETS = false;
  34788. _this.MORPHTARGETS_NORMAL = false;
  34789. _this.MORPHTARGETS_TANGENT = false;
  34790. _this.NUM_MORPH_INFLUENCERS = 0;
  34791. _this.IMAGEPROCESSING = false;
  34792. _this.VIGNETTE = false;
  34793. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34794. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34795. _this.TONEMAPPING = false;
  34796. _this.CONTRAST = false;
  34797. _this.COLORCURVES = false;
  34798. _this.COLORGRADING = false;
  34799. _this.COLORGRADING3D = false;
  34800. _this.SAMPLER3DGREENDEPTH = false;
  34801. _this.SAMPLER3DBGRMAP = false;
  34802. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34803. _this.EXPOSURE = false;
  34804. _this.USEPHYSICALLIGHTFALLOFF = false;
  34805. _this.TWOSIDEDLIGHTING = false;
  34806. _this.SHADOWFLOAT = false;
  34807. _this.CLIPPLANE = false;
  34808. _this.POINTSIZE = false;
  34809. _this.FOG = false;
  34810. _this.LOGARITHMICDEPTH = false;
  34811. _this.FORCENORMALFORWARD = false;
  34812. _this.rebuild();
  34813. return _this;
  34814. }
  34815. PBRMaterialDefines.prototype.reset = function () {
  34816. _super.prototype.reset.call(this);
  34817. this.ALPHATESTVALUE = 0.5;
  34818. this.PBR = true;
  34819. };
  34820. return PBRMaterialDefines;
  34821. }(BABYLON.MaterialDefines));
  34822. /**
  34823. * The Physically based material base class of BJS.
  34824. *
  34825. * This offers the main features of a standard PBR material.
  34826. * For more information, please refer to the documentation :
  34827. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34828. */
  34829. var PBRBaseMaterial = /** @class */ (function (_super) {
  34830. __extends(PBRBaseMaterial, _super);
  34831. /**
  34832. * Instantiates a new PBRMaterial instance.
  34833. *
  34834. * @param name The material name
  34835. * @param scene The scene the material will be use in.
  34836. */
  34837. function PBRBaseMaterial(name, scene) {
  34838. var _this = _super.call(this, name, scene) || this;
  34839. /**
  34840. * Intensity of the direct lights e.g. the four lights available in your scene.
  34841. * This impacts both the direct diffuse and specular highlights.
  34842. */
  34843. _this._directIntensity = 1.0;
  34844. /**
  34845. * Intensity of the emissive part of the material.
  34846. * This helps controlling the emissive effect without modifying the emissive color.
  34847. */
  34848. _this._emissiveIntensity = 1.0;
  34849. /**
  34850. * Intensity of the environment e.g. how much the environment will light the object
  34851. * either through harmonics for rough material or through the refelction for shiny ones.
  34852. */
  34853. _this._environmentIntensity = 1.0;
  34854. /**
  34855. * This is a special control allowing the reduction of the specular highlights coming from the
  34856. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34857. */
  34858. _this._specularIntensity = 1.0;
  34859. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34860. /**
  34861. * Debug Control allowing disabling the bump map on this material.
  34862. */
  34863. _this._disableBumpMap = false;
  34864. /**
  34865. * AKA Occlusion Texture Intensity in other nomenclature.
  34866. */
  34867. _this._ambientTextureStrength = 1.0;
  34868. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34869. /**
  34870. * AKA Diffuse Color in other nomenclature.
  34871. */
  34872. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34873. /**
  34874. * AKA Specular Color in other nomenclature.
  34875. */
  34876. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34877. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34878. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34879. /**
  34880. * AKA Glossiness in other nomenclature.
  34881. */
  34882. _this._microSurface = 0.9;
  34883. /**
  34884. * source material index of refraction (IOR)' / 'destination material IOR.
  34885. */
  34886. _this._indexOfRefraction = 0.66;
  34887. /**
  34888. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34889. */
  34890. _this._invertRefractionY = false;
  34891. /**
  34892. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34893. * Materials half opaque for instance using refraction could benefit from this control.
  34894. */
  34895. _this._linkRefractionWithTransparency = false;
  34896. _this._useLightmapAsShadowmap = false;
  34897. /**
  34898. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34899. */
  34900. _this._useAlphaFromAlbedoTexture = false;
  34901. /**
  34902. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34903. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34904. */
  34905. _this._useSpecularOverAlpha = true;
  34906. /**
  34907. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34908. */
  34909. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34910. /**
  34911. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34912. */
  34913. _this._useRoughnessFromMetallicTextureAlpha = true;
  34914. /**
  34915. * Specifies if the metallic texture contains the roughness information in its green channel.
  34916. */
  34917. _this._useRoughnessFromMetallicTextureGreen = false;
  34918. /**
  34919. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34920. */
  34921. _this._useMetallnessFromMetallicTextureBlue = false;
  34922. /**
  34923. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34924. */
  34925. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34926. /**
  34927. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34928. */
  34929. _this._useAmbientInGrayScale = false;
  34930. /**
  34931. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34932. * The material will try to infer what glossiness each pixel should be.
  34933. */
  34934. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34935. /**
  34936. * BJS is using an harcoded light falloff based on a manually sets up range.
  34937. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34938. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34939. */
  34940. _this._usePhysicalLightFalloff = true;
  34941. /**
  34942. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34943. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34944. */
  34945. _this._useRadianceOverAlpha = true;
  34946. /**
  34947. * Allows using the bump map in parallax mode.
  34948. */
  34949. _this._useParallax = false;
  34950. /**
  34951. * Allows using the bump map in parallax occlusion mode.
  34952. */
  34953. _this._useParallaxOcclusion = false;
  34954. /**
  34955. * Controls the scale bias of the parallax mode.
  34956. */
  34957. _this._parallaxScaleBias = 0.05;
  34958. /**
  34959. * If sets to true, disables all the lights affecting the material.
  34960. */
  34961. _this._disableLighting = false;
  34962. /**
  34963. * Number of Simultaneous lights allowed on the material.
  34964. */
  34965. _this._maxSimultaneousLights = 4;
  34966. /**
  34967. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34968. */
  34969. _this._invertNormalMapX = false;
  34970. /**
  34971. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34972. */
  34973. _this._invertNormalMapY = false;
  34974. /**
  34975. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34976. */
  34977. _this._twoSidedLighting = false;
  34978. /**
  34979. * Defines the alpha limits in alpha test mode.
  34980. */
  34981. _this._alphaCutOff = 0.4;
  34982. /**
  34983. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34984. */
  34985. _this._forceAlphaTest = false;
  34986. /**
  34987. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34988. * And/Or occlude the blended part.
  34989. */
  34990. _this._useAlphaFresnel = false;
  34991. /**
  34992. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34993. * from cos thetav and roughness:
  34994. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34995. */
  34996. _this._environmentBRDFTexture = null;
  34997. /**
  34998. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34999. */
  35000. _this._forceIrradianceInFragment = false;
  35001. /**
  35002. * Force normal to face away from face.
  35003. * (Temporary internal fix to remove before 3.1)
  35004. */
  35005. _this._forceNormalForward = false;
  35006. _this._renderTargets = new BABYLON.SmartArray(16);
  35007. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35008. // Setup the default processing configuration to the scene.
  35009. _this._attachImageProcessingConfiguration(null);
  35010. _this.getRenderTargetTextures = function () {
  35011. _this._renderTargets.reset();
  35012. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35013. _this._renderTargets.push(_this._reflectionTexture);
  35014. }
  35015. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35016. _this._renderTargets.push(_this._refractionTexture);
  35017. }
  35018. return _this._renderTargets;
  35019. };
  35020. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35021. return _this;
  35022. }
  35023. /**
  35024. * Attaches a new image processing configuration to the PBR Material.
  35025. * @param configuration
  35026. */
  35027. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35028. var _this = this;
  35029. if (configuration === this._imageProcessingConfiguration) {
  35030. return;
  35031. }
  35032. // Detaches observer.
  35033. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35034. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35035. }
  35036. // Pick the scene configuration if needed.
  35037. if (!configuration) {
  35038. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35039. }
  35040. else {
  35041. this._imageProcessingConfiguration = configuration;
  35042. }
  35043. // Attaches observer.
  35044. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35045. _this._markAllSubMeshesAsImageProcessingDirty();
  35046. });
  35047. };
  35048. PBRBaseMaterial.prototype.getClassName = function () {
  35049. return "PBRBaseMaterial";
  35050. };
  35051. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35052. get: function () {
  35053. return this._useLogarithmicDepth;
  35054. },
  35055. set: function (value) {
  35056. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35062. if (this._linkRefractionWithTransparency) {
  35063. return false;
  35064. }
  35065. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35066. };
  35067. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35068. if (this._forceAlphaTest) {
  35069. return true;
  35070. }
  35071. if (this._linkRefractionWithTransparency) {
  35072. return false;
  35073. }
  35074. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  35075. };
  35076. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35077. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  35078. };
  35079. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35080. return this._albedoTexture;
  35081. };
  35082. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35083. var _this = this;
  35084. if (subMesh.effect && this.isFrozen) {
  35085. if (this._wasPreviouslyReady) {
  35086. return true;
  35087. }
  35088. }
  35089. if (!subMesh._materialDefines) {
  35090. subMesh._materialDefines = new PBRMaterialDefines();
  35091. }
  35092. var scene = this.getScene();
  35093. var defines = subMesh._materialDefines;
  35094. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35095. if (defines._renderId === scene.getRenderId()) {
  35096. return true;
  35097. }
  35098. }
  35099. var engine = scene.getEngine();
  35100. // Lights
  35101. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35102. defines._needNormals = true;
  35103. // Textures
  35104. if (defines._areTexturesDirty) {
  35105. defines._needUVs = false;
  35106. if (scene.texturesEnabled) {
  35107. if (scene.getEngine().getCaps().textureLOD) {
  35108. defines.LODBASEDMICROSFURACE = true;
  35109. }
  35110. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35111. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35112. return false;
  35113. }
  35114. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35115. }
  35116. else {
  35117. defines.ALBEDO = false;
  35118. }
  35119. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35120. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35121. return false;
  35122. }
  35123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35124. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35125. }
  35126. else {
  35127. defines.AMBIENT = false;
  35128. }
  35129. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35130. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35131. return false;
  35132. }
  35133. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35134. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35135. }
  35136. else {
  35137. defines.OPACITY = false;
  35138. }
  35139. var reflectionTexture = this._getReflectionTexture();
  35140. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35141. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35142. return false;
  35143. }
  35144. defines.REFLECTION = true;
  35145. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35146. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35147. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35148. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35149. defines.INVERTCUBICMAP = true;
  35150. }
  35151. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35152. switch (reflectionTexture.coordinatesMode) {
  35153. case BABYLON.Texture.CUBIC_MODE:
  35154. case BABYLON.Texture.INVCUBIC_MODE:
  35155. defines.REFLECTIONMAP_CUBIC = true;
  35156. break;
  35157. case BABYLON.Texture.EXPLICIT_MODE:
  35158. defines.REFLECTIONMAP_EXPLICIT = true;
  35159. break;
  35160. case BABYLON.Texture.PLANAR_MODE:
  35161. defines.REFLECTIONMAP_PLANAR = true;
  35162. break;
  35163. case BABYLON.Texture.PROJECTION_MODE:
  35164. defines.REFLECTIONMAP_PROJECTION = true;
  35165. break;
  35166. case BABYLON.Texture.SKYBOX_MODE:
  35167. defines.REFLECTIONMAP_SKYBOX = true;
  35168. break;
  35169. case BABYLON.Texture.SPHERICAL_MODE:
  35170. defines.REFLECTIONMAP_SPHERICAL = true;
  35171. break;
  35172. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35173. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35174. break;
  35175. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35176. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35177. break;
  35178. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35179. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35180. break;
  35181. }
  35182. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35183. if (reflectionTexture.sphericalPolynomial) {
  35184. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35185. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35186. defines.USESPHERICALINVERTEX = false;
  35187. }
  35188. else {
  35189. defines.USESPHERICALINVERTEX = true;
  35190. }
  35191. }
  35192. }
  35193. }
  35194. else {
  35195. defines.REFLECTION = false;
  35196. defines.REFLECTIONMAP_3D = false;
  35197. defines.REFLECTIONMAP_SPHERICAL = false;
  35198. defines.REFLECTIONMAP_PLANAR = false;
  35199. defines.REFLECTIONMAP_CUBIC = false;
  35200. defines.REFLECTIONMAP_PROJECTION = false;
  35201. defines.REFLECTIONMAP_SKYBOX = false;
  35202. defines.REFLECTIONMAP_EXPLICIT = false;
  35203. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35204. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35205. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35206. defines.INVERTCUBICMAP = false;
  35207. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35208. defines.USESPHERICALINVERTEX = false;
  35209. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35210. defines.LODINREFLECTIONALPHA = false;
  35211. defines.GAMMAREFLECTION = false;
  35212. }
  35213. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35214. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35215. return false;
  35216. }
  35217. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35218. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35219. }
  35220. else {
  35221. defines.LIGHTMAP = false;
  35222. }
  35223. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35224. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35225. return false;
  35226. }
  35227. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35228. }
  35229. else {
  35230. defines.EMISSIVE = false;
  35231. }
  35232. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35233. if (this._metallicTexture) {
  35234. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35235. return false;
  35236. }
  35237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35238. defines.METALLICWORKFLOW = true;
  35239. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35240. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35241. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35242. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35243. }
  35244. else if (this._reflectivityTexture) {
  35245. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35246. return false;
  35247. }
  35248. defines.METALLICWORKFLOW = false;
  35249. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35250. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35251. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35252. }
  35253. else {
  35254. defines.METALLICWORKFLOW = false;
  35255. defines.REFLECTIVITY = false;
  35256. }
  35257. if (this._microSurfaceTexture) {
  35258. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35259. return false;
  35260. }
  35261. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35262. }
  35263. else {
  35264. defines.MICROSURFACEMAP = false;
  35265. }
  35266. }
  35267. else {
  35268. defines.REFLECTIVITY = false;
  35269. defines.MICROSURFACEMAP = false;
  35270. }
  35271. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35272. // Bump texure can not be none blocking.
  35273. if (!this._bumpTexture.isReady()) {
  35274. return false;
  35275. }
  35276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35277. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35278. defines.PARALLAX = true;
  35279. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35280. }
  35281. else {
  35282. defines.PARALLAX = false;
  35283. }
  35284. }
  35285. else {
  35286. defines.BUMP = false;
  35287. }
  35288. var refractionTexture = this._getRefractionTexture();
  35289. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35290. if (!refractionTexture.isReadyOrNotBlocking()) {
  35291. return false;
  35292. }
  35293. defines.REFRACTION = true;
  35294. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35295. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35296. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35297. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35298. if (this._linkRefractionWithTransparency) {
  35299. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35300. }
  35301. }
  35302. else {
  35303. defines.REFRACTION = false;
  35304. }
  35305. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35306. // This is blocking.
  35307. if (!this._environmentBRDFTexture.isReady()) {
  35308. return false;
  35309. }
  35310. defines.ENVIRONMENTBRDF = true;
  35311. }
  35312. else {
  35313. defines.ENVIRONMENTBRDF = false;
  35314. }
  35315. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35316. defines.ALPHAFROMALBEDO = true;
  35317. }
  35318. else {
  35319. defines.ALPHAFROMALBEDO = false;
  35320. }
  35321. }
  35322. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35323. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35324. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35325. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35326. defines.METALLICWORKFLOW = true;
  35327. }
  35328. else {
  35329. defines.METALLICWORKFLOW = false;
  35330. }
  35331. if (!this.backFaceCulling && this._twoSidedLighting) {
  35332. defines.TWOSIDEDLIGHTING = true;
  35333. }
  35334. else {
  35335. defines.TWOSIDEDLIGHTING = false;
  35336. }
  35337. defines.ALPHATESTVALUE = this._alphaCutOff;
  35338. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35339. defines.ALPHABLEND = this.needAlphaBlending();
  35340. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35341. }
  35342. if (defines._areImageProcessingDirty) {
  35343. if (!this._imageProcessingConfiguration.isReady()) {
  35344. return false;
  35345. }
  35346. this._imageProcessingConfiguration.prepareDefines(defines);
  35347. }
  35348. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35349. // Misc.
  35350. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35351. // Values that need to be evaluated on every frame
  35352. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35353. // Attribs
  35354. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35355. if (mesh) {
  35356. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35357. mesh.createNormals(true);
  35358. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35359. }
  35360. }
  35361. }
  35362. // Get correct effect
  35363. if (defines.isDirty) {
  35364. defines.markAsProcessed();
  35365. scene.resetCachedMaterial();
  35366. // Fallbacks
  35367. var fallbacks = new BABYLON.EffectFallbacks();
  35368. var fallbackRank = 0;
  35369. if (defines.USESPHERICALINVERTEX) {
  35370. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35371. }
  35372. if (defines.FOG) {
  35373. fallbacks.addFallback(fallbackRank, "FOG");
  35374. }
  35375. if (defines.POINTSIZE) {
  35376. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35377. }
  35378. if (defines.LOGARITHMICDEPTH) {
  35379. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35380. }
  35381. if (defines.PARALLAX) {
  35382. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35383. }
  35384. if (defines.PARALLAXOCCLUSION) {
  35385. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35386. }
  35387. if (defines.ENVIRONMENTBRDF) {
  35388. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35389. }
  35390. if (defines.TANGENT) {
  35391. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35392. }
  35393. if (defines.BUMP) {
  35394. fallbacks.addFallback(fallbackRank++, "BUMP");
  35395. }
  35396. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35397. if (defines.SPECULARTERM) {
  35398. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35399. }
  35400. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35401. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35402. }
  35403. if (defines.LIGHTMAP) {
  35404. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35405. }
  35406. if (defines.NORMAL) {
  35407. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35408. }
  35409. if (defines.AMBIENT) {
  35410. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35411. }
  35412. if (defines.EMISSIVE) {
  35413. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35414. }
  35415. if (defines.VERTEXCOLOR) {
  35416. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35417. }
  35418. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35419. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35420. }
  35421. if (defines.MORPHTARGETS) {
  35422. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35423. }
  35424. //Attributes
  35425. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35426. if (defines.NORMAL) {
  35427. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35428. }
  35429. if (defines.TANGENT) {
  35430. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35431. }
  35432. if (defines.UV1) {
  35433. attribs.push(BABYLON.VertexBuffer.UVKind);
  35434. }
  35435. if (defines.UV2) {
  35436. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35437. }
  35438. if (defines.VERTEXCOLOR) {
  35439. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35440. }
  35441. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35442. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35443. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35444. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35445. "vFogInfos", "vFogColor", "pointSize",
  35446. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35447. "mBones",
  35448. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35449. "vLightingIntensity",
  35450. "logarithmicDepthConstant",
  35451. "vSphericalX", "vSphericalY", "vSphericalZ",
  35452. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35453. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35454. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35455. "vTangentSpaceParams"
  35456. ];
  35457. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35458. "bumpSampler", "lightmapSampler", "opacitySampler",
  35459. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35460. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35461. "microSurfaceSampler", "environmentBrdfSampler"];
  35462. var uniformBuffers = ["Material", "Scene"];
  35463. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35464. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35465. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35466. uniformsNames: uniforms,
  35467. uniformBuffersNames: uniformBuffers,
  35468. samplers: samplers,
  35469. defines: defines,
  35470. maxSimultaneousLights: this._maxSimultaneousLights
  35471. });
  35472. var onCompiled = function (effect) {
  35473. if (_this.onCompiled) {
  35474. _this.onCompiled(effect);
  35475. }
  35476. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35477. };
  35478. var join = defines.toString();
  35479. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35480. attributes: attribs,
  35481. uniformsNames: uniforms,
  35482. uniformBuffersNames: uniformBuffers,
  35483. samplers: samplers,
  35484. defines: join,
  35485. fallbacks: fallbacks,
  35486. onCompiled: onCompiled,
  35487. onError: this.onError,
  35488. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35489. }, engine), defines);
  35490. this.buildUniformLayout();
  35491. }
  35492. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35493. return false;
  35494. }
  35495. defines._renderId = scene.getRenderId();
  35496. this._wasPreviouslyReady = true;
  35497. return true;
  35498. };
  35499. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35500. // Order is important !
  35501. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35502. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35503. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35504. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35505. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35506. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35507. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35508. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35509. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35510. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35511. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35512. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35513. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35514. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35515. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35516. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35517. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35518. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35519. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35520. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35521. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35522. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35523. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35524. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35525. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35526. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35527. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35528. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35529. this._uniformBuffer.addUniform("pointSize", 1);
  35530. this._uniformBuffer.create();
  35531. };
  35532. PBRBaseMaterial.prototype.unbind = function () {
  35533. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35534. this._uniformBuffer.setTexture("reflectionSampler", null);
  35535. }
  35536. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35537. this._uniformBuffer.setTexture("refractionSampler", null);
  35538. }
  35539. _super.prototype.unbind.call(this);
  35540. };
  35541. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35542. this._activeEffect.setMatrix("world", world);
  35543. };
  35544. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35545. var scene = this.getScene();
  35546. var defines = subMesh._materialDefines;
  35547. if (!defines) {
  35548. return;
  35549. }
  35550. var effect = subMesh.effect;
  35551. if (!effect) {
  35552. return;
  35553. }
  35554. this._activeEffect = effect;
  35555. // Matrices
  35556. this.bindOnlyWorldMatrix(world);
  35557. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35558. // Bones
  35559. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35560. var reflectionTexture = null;
  35561. if (mustRebind) {
  35562. this._uniformBuffer.bindToEffect(effect, "Material");
  35563. this.bindViewProjection(effect);
  35564. reflectionTexture = this._getReflectionTexture();
  35565. var refractionTexture = this._getRefractionTexture();
  35566. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35567. // Texture uniforms
  35568. if (scene.texturesEnabled) {
  35569. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35570. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35571. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35572. }
  35573. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35574. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35575. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35576. }
  35577. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35578. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35579. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35580. }
  35581. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35582. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35583. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35584. var polynomials = reflectionTexture.sphericalPolynomial;
  35585. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35586. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35587. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35588. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35589. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35590. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35591. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35592. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35593. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35594. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35595. }
  35596. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35597. }
  35598. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35599. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35600. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35601. }
  35602. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35603. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35604. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35605. }
  35606. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35607. if (this._metallicTexture) {
  35608. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35609. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35610. }
  35611. else if (this._reflectivityTexture) {
  35612. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35613. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35614. }
  35615. if (this._microSurfaceTexture) {
  35616. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35617. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35618. }
  35619. }
  35620. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35621. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35622. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35623. if (scene._mirroredCameraPosition) {
  35624. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35625. }
  35626. else {
  35627. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35628. }
  35629. }
  35630. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35631. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35632. var depth = 1.0;
  35633. if (!refractionTexture.isCube) {
  35634. if (refractionTexture.depth) {
  35635. depth = refractionTexture.depth;
  35636. }
  35637. }
  35638. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35639. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35640. }
  35641. }
  35642. // Point size
  35643. if (this.pointsCloud) {
  35644. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35645. }
  35646. // Colors
  35647. if (defines.METALLICWORKFLOW) {
  35648. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35649. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35650. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35651. }
  35652. else {
  35653. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35654. }
  35655. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35656. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35657. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35658. // Misc
  35659. this._lightingInfos.x = this._directIntensity;
  35660. this._lightingInfos.y = this._emissiveIntensity;
  35661. this._lightingInfos.z = this._environmentIntensity;
  35662. this._lightingInfos.w = this._specularIntensity;
  35663. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35664. }
  35665. // Textures
  35666. if (scene.texturesEnabled) {
  35667. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35668. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35669. }
  35670. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35671. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35672. }
  35673. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35674. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35675. }
  35676. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35677. if (defines.LODBASEDMICROSFURACE) {
  35678. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35679. }
  35680. else {
  35681. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35682. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35683. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35684. }
  35685. }
  35686. if (defines.ENVIRONMENTBRDF) {
  35687. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35688. }
  35689. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35690. if (defines.LODBASEDMICROSFURACE) {
  35691. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35692. }
  35693. else {
  35694. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35695. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35696. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35697. }
  35698. }
  35699. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35700. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35701. }
  35702. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35703. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35704. }
  35705. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35706. if (this._metallicTexture) {
  35707. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35708. }
  35709. else if (this._reflectivityTexture) {
  35710. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35711. }
  35712. if (this._microSurfaceTexture) {
  35713. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35714. }
  35715. }
  35716. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35717. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35718. }
  35719. }
  35720. // Clip plane
  35721. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35722. // Colors
  35723. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35724. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35725. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35726. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35727. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35728. }
  35729. if (mustRebind || !this.isFrozen) {
  35730. // Lights
  35731. if (scene.lightsEnabled && !this._disableLighting) {
  35732. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35733. }
  35734. // View
  35735. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35736. this.bindView(effect);
  35737. }
  35738. // Fog
  35739. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35740. // Morph targets
  35741. if (defines.NUM_MORPH_INFLUENCERS) {
  35742. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35743. }
  35744. // image processing
  35745. this._imageProcessingConfiguration.bind(this._activeEffect);
  35746. // Log. depth
  35747. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35748. }
  35749. this._uniformBuffer.update();
  35750. this._afterBind(mesh);
  35751. };
  35752. PBRBaseMaterial.prototype.getAnimatables = function () {
  35753. var results = [];
  35754. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35755. results.push(this._albedoTexture);
  35756. }
  35757. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35758. results.push(this._ambientTexture);
  35759. }
  35760. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35761. results.push(this._opacityTexture);
  35762. }
  35763. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35764. results.push(this._reflectionTexture);
  35765. }
  35766. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35767. results.push(this._emissiveTexture);
  35768. }
  35769. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35770. results.push(this._metallicTexture);
  35771. }
  35772. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35773. results.push(this._reflectivityTexture);
  35774. }
  35775. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35776. results.push(this._bumpTexture);
  35777. }
  35778. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35779. results.push(this._lightmapTexture);
  35780. }
  35781. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35782. results.push(this._refractionTexture);
  35783. }
  35784. return results;
  35785. };
  35786. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35787. if (this._reflectionTexture) {
  35788. return this._reflectionTexture;
  35789. }
  35790. return this.getScene().environmentTexture;
  35791. };
  35792. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35793. if (this._refractionTexture) {
  35794. return this._refractionTexture;
  35795. }
  35796. if (this._linkRefractionWithTransparency) {
  35797. return this.getScene().environmentTexture;
  35798. }
  35799. return null;
  35800. };
  35801. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35802. if (forceDisposeTextures) {
  35803. if (this._albedoTexture) {
  35804. this._albedoTexture.dispose();
  35805. }
  35806. if (this._ambientTexture) {
  35807. this._ambientTexture.dispose();
  35808. }
  35809. if (this._opacityTexture) {
  35810. this._opacityTexture.dispose();
  35811. }
  35812. if (this._reflectionTexture) {
  35813. this._reflectionTexture.dispose();
  35814. }
  35815. if (this._environmentBRDFTexture) {
  35816. this._environmentBRDFTexture.dispose();
  35817. }
  35818. if (this._emissiveTexture) {
  35819. this._emissiveTexture.dispose();
  35820. }
  35821. if (this._metallicTexture) {
  35822. this._metallicTexture.dispose();
  35823. }
  35824. if (this._reflectivityTexture) {
  35825. this._reflectivityTexture.dispose();
  35826. }
  35827. if (this._bumpTexture) {
  35828. this._bumpTexture.dispose();
  35829. }
  35830. if (this._lightmapTexture) {
  35831. this._lightmapTexture.dispose();
  35832. }
  35833. if (this._refractionTexture) {
  35834. this._refractionTexture.dispose();
  35835. }
  35836. }
  35837. this._renderTargets.dispose();
  35838. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35839. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35840. }
  35841. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35842. };
  35843. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35844. __decorate([
  35845. BABYLON.serializeAsImageProcessingConfiguration()
  35846. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35847. __decorate([
  35848. BABYLON.serialize()
  35849. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35850. return PBRBaseMaterial;
  35851. }(BABYLON.PushMaterial));
  35852. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35853. })(BABYLON || (BABYLON = {}));
  35854. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35855. var BABYLON;
  35856. (function (BABYLON) {
  35857. var Internals;
  35858. (function (Internals) {
  35859. /**
  35860. * The Physically based simple base material of BJS.
  35861. *
  35862. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35863. * It is used as the base class for both the specGloss and metalRough conventions.
  35864. */
  35865. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35866. __extends(PBRBaseSimpleMaterial, _super);
  35867. /**
  35868. * Instantiates a new PBRMaterial instance.
  35869. *
  35870. * @param name The material name
  35871. * @param scene The scene the material will be use in.
  35872. */
  35873. function PBRBaseSimpleMaterial(name, scene) {
  35874. var _this = _super.call(this, name, scene) || this;
  35875. /**
  35876. * Number of Simultaneous lights allowed on the material.
  35877. */
  35878. _this.maxSimultaneousLights = 4;
  35879. /**
  35880. * If sets to true, disables all the lights affecting the material.
  35881. */
  35882. _this.disableLighting = false;
  35883. /**
  35884. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35885. */
  35886. _this.invertNormalMapX = false;
  35887. /**
  35888. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35889. */
  35890. _this.invertNormalMapY = false;
  35891. /**
  35892. * Emissivie color used to self-illuminate the model.
  35893. */
  35894. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35895. /**
  35896. * Occlusion Channel Strenght.
  35897. */
  35898. _this.occlusionStrength = 1.0;
  35899. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35900. _this._useAmbientInGrayScale = true;
  35901. return _this;
  35902. }
  35903. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35904. /**
  35905. * Gets the current transparency mode.
  35906. */
  35907. get: function () {
  35908. return this._transparencyMode;
  35909. },
  35910. /**
  35911. * Sets the transparency mode of the material.
  35912. */
  35913. set: function (value) {
  35914. if (this._transparencyMode === value) {
  35915. return;
  35916. }
  35917. this._transparencyMode = value;
  35918. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35919. this._forceAlphaTest = true;
  35920. }
  35921. else {
  35922. this._forceAlphaTest = false;
  35923. }
  35924. this._markAllSubMeshesAsTexturesDirty();
  35925. },
  35926. enumerable: true,
  35927. configurable: true
  35928. });
  35929. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35930. /**
  35931. * Gets the current double sided mode.
  35932. */
  35933. get: function () {
  35934. return this._twoSidedLighting;
  35935. },
  35936. /**
  35937. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35938. */
  35939. set: function (value) {
  35940. if (this._twoSidedLighting === value) {
  35941. return;
  35942. }
  35943. this._twoSidedLighting = value;
  35944. this.backFaceCulling = !value;
  35945. this._markAllSubMeshesAsTexturesDirty();
  35946. },
  35947. enumerable: true,
  35948. configurable: true
  35949. });
  35950. /**
  35951. * Specifies wether or not the alpha value of the albedo texture should be used.
  35952. */
  35953. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35954. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35955. };
  35956. /**
  35957. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35958. */
  35959. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35960. if (this._linkRefractionWithTransparency) {
  35961. return false;
  35962. }
  35963. return (this.alpha < 1.0) ||
  35964. (this._shouldUseAlphaFromAlbedoTexture() &&
  35965. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35966. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35967. };
  35968. /**
  35969. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35970. */
  35971. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35972. if (this._linkRefractionWithTransparency) {
  35973. return false;
  35974. }
  35975. return this._shouldUseAlphaFromAlbedoTexture() &&
  35976. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35977. };
  35978. /**
  35979. * Return the active textures of the material.
  35980. */
  35981. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35982. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35983. if (this.environmentTexture) {
  35984. activeTextures.push(this.environmentTexture);
  35985. }
  35986. if (this.normalTexture) {
  35987. activeTextures.push(this.normalTexture);
  35988. }
  35989. if (this.emissiveTexture) {
  35990. activeTextures.push(this.emissiveTexture);
  35991. }
  35992. if (this.occlusionTexture) {
  35993. activeTextures.push(this.occlusionTexture);
  35994. }
  35995. return activeTextures;
  35996. };
  35997. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35998. return "PBRBaseSimpleMaterial";
  35999. };
  36000. __decorate([
  36001. BABYLON.serialize(),
  36002. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36003. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36004. __decorate([
  36005. BABYLON.serialize(),
  36006. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36007. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36008. __decorate([
  36009. BABYLON.serializeAsTexture(),
  36010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36011. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36012. __decorate([
  36013. BABYLON.serialize(),
  36014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36015. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36016. __decorate([
  36017. BABYLON.serialize(),
  36018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36019. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36020. __decorate([
  36021. BABYLON.serializeAsTexture(),
  36022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36023. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36024. __decorate([
  36025. BABYLON.serializeAsColor3("emissive"),
  36026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36027. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36028. __decorate([
  36029. BABYLON.serializeAsTexture(),
  36030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36031. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36032. __decorate([
  36033. BABYLON.serialize(),
  36034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36035. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36036. __decorate([
  36037. BABYLON.serializeAsTexture(),
  36038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36039. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36040. __decorate([
  36041. BABYLON.serialize(),
  36042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36043. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36044. __decorate([
  36045. BABYLON.serialize()
  36046. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  36047. __decorate([
  36048. BABYLON.serialize()
  36049. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36050. return PBRBaseSimpleMaterial;
  36051. }(BABYLON.PBRBaseMaterial));
  36052. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36053. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36054. })(BABYLON || (BABYLON = {}));
  36055. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36056. var BABYLON;
  36057. (function (BABYLON) {
  36058. /**
  36059. * The Physically based material of BJS.
  36060. *
  36061. * This offers the main features of a standard PBR material.
  36062. * For more information, please refer to the documentation :
  36063. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36064. */
  36065. var PBRMaterial = /** @class */ (function (_super) {
  36066. __extends(PBRMaterial, _super);
  36067. /**
  36068. * Instantiates a new PBRMaterial instance.
  36069. *
  36070. * @param name The material name
  36071. * @param scene The scene the material will be use in.
  36072. */
  36073. function PBRMaterial(name, scene) {
  36074. var _this = _super.call(this, name, scene) || this;
  36075. /**
  36076. * Intensity of the direct lights e.g. the four lights available in your scene.
  36077. * This impacts both the direct diffuse and specular highlights.
  36078. */
  36079. _this.directIntensity = 1.0;
  36080. /**
  36081. * Intensity of the emissive part of the material.
  36082. * This helps controlling the emissive effect without modifying the emissive color.
  36083. */
  36084. _this.emissiveIntensity = 1.0;
  36085. /**
  36086. * Intensity of the environment e.g. how much the environment will light the object
  36087. * either through harmonics for rough material or through the refelction for shiny ones.
  36088. */
  36089. _this.environmentIntensity = 1.0;
  36090. /**
  36091. * This is a special control allowing the reduction of the specular highlights coming from the
  36092. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36093. */
  36094. _this.specularIntensity = 1.0;
  36095. /**
  36096. * Debug Control allowing disabling the bump map on this material.
  36097. */
  36098. _this.disableBumpMap = false;
  36099. /**
  36100. * AKA Occlusion Texture Intensity in other nomenclature.
  36101. */
  36102. _this.ambientTextureStrength = 1.0;
  36103. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36104. /**
  36105. * AKA Diffuse Color in other nomenclature.
  36106. */
  36107. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36108. /**
  36109. * AKA Specular Color in other nomenclature.
  36110. */
  36111. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36112. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36113. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36114. /**
  36115. * AKA Glossiness in other nomenclature.
  36116. */
  36117. _this.microSurface = 1.0;
  36118. /**
  36119. * source material index of refraction (IOR)' / 'destination material IOR.
  36120. */
  36121. _this.indexOfRefraction = 0.66;
  36122. /**
  36123. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36124. */
  36125. _this.invertRefractionY = false;
  36126. /**
  36127. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36128. * Materials half opaque for instance using refraction could benefit from this control.
  36129. */
  36130. _this.linkRefractionWithTransparency = false;
  36131. _this.useLightmapAsShadowmap = false;
  36132. /**
  36133. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36134. */
  36135. _this.useAlphaFromAlbedoTexture = false;
  36136. /**
  36137. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36138. */
  36139. _this.forceAlphaTest = false;
  36140. /**
  36141. * Defines the alpha limits in alpha test mode.
  36142. */
  36143. _this.alphaCutOff = 0.4;
  36144. /**
  36145. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36146. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36147. */
  36148. _this.useSpecularOverAlpha = true;
  36149. /**
  36150. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36151. */
  36152. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36153. /**
  36154. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36155. */
  36156. _this.useRoughnessFromMetallicTextureAlpha = true;
  36157. /**
  36158. * Specifies if the metallic texture contains the roughness information in its green channel.
  36159. */
  36160. _this.useRoughnessFromMetallicTextureGreen = false;
  36161. /**
  36162. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36163. */
  36164. _this.useMetallnessFromMetallicTextureBlue = false;
  36165. /**
  36166. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36167. */
  36168. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36169. /**
  36170. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36171. */
  36172. _this.useAmbientInGrayScale = false;
  36173. /**
  36174. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36175. * The material will try to infer what glossiness each pixel should be.
  36176. */
  36177. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36178. /**
  36179. * BJS is using an harcoded light falloff based on a manually sets up range.
  36180. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36181. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36182. */
  36183. _this.usePhysicalLightFalloff = true;
  36184. /**
  36185. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36186. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36187. */
  36188. _this.useRadianceOverAlpha = true;
  36189. /**
  36190. * Allows using the bump map in parallax mode.
  36191. */
  36192. _this.useParallax = false;
  36193. /**
  36194. * Allows using the bump map in parallax occlusion mode.
  36195. */
  36196. _this.useParallaxOcclusion = false;
  36197. /**
  36198. * Controls the scale bias of the parallax mode.
  36199. */
  36200. _this.parallaxScaleBias = 0.05;
  36201. /**
  36202. * If sets to true, disables all the lights affecting the material.
  36203. */
  36204. _this.disableLighting = false;
  36205. /**
  36206. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36207. */
  36208. _this.forceIrradianceInFragment = false;
  36209. /**
  36210. * Number of Simultaneous lights allowed on the material.
  36211. */
  36212. _this.maxSimultaneousLights = 4;
  36213. /**
  36214. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36215. */
  36216. _this.invertNormalMapX = false;
  36217. /**
  36218. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36219. */
  36220. _this.invertNormalMapY = false;
  36221. /**
  36222. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36223. */
  36224. _this.twoSidedLighting = false;
  36225. /**
  36226. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36227. * And/Or occlude the blended part.
  36228. */
  36229. _this.useAlphaFresnel = false;
  36230. /**
  36231. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36232. * And/Or occlude the blended part.
  36233. */
  36234. _this.environmentBRDFTexture = null;
  36235. /**
  36236. * Force normal to face away from face.
  36237. * (Temporary internal fix to remove before 3.1)
  36238. */
  36239. _this.forceNormalForward = false;
  36240. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36241. return _this;
  36242. }
  36243. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36244. /**
  36245. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36246. */
  36247. get: function () {
  36248. return this._PBRMATERIAL_OPAQUE;
  36249. },
  36250. enumerable: true,
  36251. configurable: true
  36252. });
  36253. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36254. /**
  36255. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36256. */
  36257. get: function () {
  36258. return this._PBRMATERIAL_ALPHATEST;
  36259. },
  36260. enumerable: true,
  36261. configurable: true
  36262. });
  36263. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36264. /**
  36265. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36266. */
  36267. get: function () {
  36268. return this._PBRMATERIAL_ALPHABLEND;
  36269. },
  36270. enumerable: true,
  36271. configurable: true
  36272. });
  36273. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36274. /**
  36275. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36276. * They are also discarded below the alpha cutoff threshold to improve performances.
  36277. */
  36278. get: function () {
  36279. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36280. },
  36281. enumerable: true,
  36282. configurable: true
  36283. });
  36284. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36285. /**
  36286. * Gets the image processing configuration used either in this material.
  36287. */
  36288. get: function () {
  36289. return this._imageProcessingConfiguration;
  36290. },
  36291. /**
  36292. * Sets the Default image processing configuration used either in the this material.
  36293. *
  36294. * If sets to null, the scene one is in use.
  36295. */
  36296. set: function (value) {
  36297. this._attachImageProcessingConfiguration(value);
  36298. // Ensure the effect will be rebuilt.
  36299. this._markAllSubMeshesAsTexturesDirty();
  36300. },
  36301. enumerable: true,
  36302. configurable: true
  36303. });
  36304. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36305. /**
  36306. * Gets wether the color curves effect is enabled.
  36307. */
  36308. get: function () {
  36309. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36310. },
  36311. /**
  36312. * Sets wether the color curves effect is enabled.
  36313. */
  36314. set: function (value) {
  36315. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36316. },
  36317. enumerable: true,
  36318. configurable: true
  36319. });
  36320. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36321. /**
  36322. * Gets wether the color grading effect is enabled.
  36323. */
  36324. get: function () {
  36325. return this.imageProcessingConfiguration.colorGradingEnabled;
  36326. },
  36327. /**
  36328. * Gets wether the color grading effect is enabled.
  36329. */
  36330. set: function (value) {
  36331. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36332. },
  36333. enumerable: true,
  36334. configurable: true
  36335. });
  36336. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36337. /**
  36338. * Gets wether tonemapping is enabled or not.
  36339. */
  36340. get: function () {
  36341. return this._imageProcessingConfiguration.toneMappingEnabled;
  36342. },
  36343. /**
  36344. * Sets wether tonemapping is enabled or not
  36345. */
  36346. set: function (value) {
  36347. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36348. },
  36349. enumerable: true,
  36350. configurable: true
  36351. });
  36352. ;
  36353. ;
  36354. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36355. /**
  36356. * The camera exposure used on this material.
  36357. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36358. * This corresponds to a photographic exposure.
  36359. */
  36360. get: function () {
  36361. return this._imageProcessingConfiguration.exposure;
  36362. },
  36363. /**
  36364. * The camera exposure used on this material.
  36365. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36366. * This corresponds to a photographic exposure.
  36367. */
  36368. set: function (value) {
  36369. this._imageProcessingConfiguration.exposure = value;
  36370. },
  36371. enumerable: true,
  36372. configurable: true
  36373. });
  36374. ;
  36375. ;
  36376. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36377. /**
  36378. * Gets The camera contrast used on this material.
  36379. */
  36380. get: function () {
  36381. return this._imageProcessingConfiguration.contrast;
  36382. },
  36383. /**
  36384. * Sets The camera contrast used on this material.
  36385. */
  36386. set: function (value) {
  36387. this._imageProcessingConfiguration.contrast = value;
  36388. },
  36389. enumerable: true,
  36390. configurable: true
  36391. });
  36392. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36393. /**
  36394. * Gets the Color Grading 2D Lookup Texture.
  36395. */
  36396. get: function () {
  36397. return this._imageProcessingConfiguration.colorGradingTexture;
  36398. },
  36399. /**
  36400. * Sets the Color Grading 2D Lookup Texture.
  36401. */
  36402. set: function (value) {
  36403. this._imageProcessingConfiguration.colorGradingTexture = value;
  36404. },
  36405. enumerable: true,
  36406. configurable: true
  36407. });
  36408. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36409. /**
  36410. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36411. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36412. * 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;
  36413. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36414. */
  36415. get: function () {
  36416. return this._imageProcessingConfiguration.colorCurves;
  36417. },
  36418. /**
  36419. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36420. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36421. * 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;
  36422. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36423. */
  36424. set: function (value) {
  36425. this._imageProcessingConfiguration.colorCurves = value;
  36426. },
  36427. enumerable: true,
  36428. configurable: true
  36429. });
  36430. PBRMaterial.prototype.getClassName = function () {
  36431. return "PBRMaterial";
  36432. };
  36433. PBRMaterial.prototype.getActiveTextures = function () {
  36434. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36435. if (this._albedoTexture) {
  36436. activeTextures.push(this._albedoTexture);
  36437. }
  36438. if (this._ambientTexture) {
  36439. activeTextures.push(this._ambientTexture);
  36440. }
  36441. if (this._opacityTexture) {
  36442. activeTextures.push(this._opacityTexture);
  36443. }
  36444. if (this._reflectionTexture) {
  36445. activeTextures.push(this._reflectionTexture);
  36446. }
  36447. if (this._emissiveTexture) {
  36448. activeTextures.push(this._emissiveTexture);
  36449. }
  36450. if (this._reflectivityTexture) {
  36451. activeTextures.push(this._reflectivityTexture);
  36452. }
  36453. if (this._metallicTexture) {
  36454. activeTextures.push(this._metallicTexture);
  36455. }
  36456. if (this._microSurfaceTexture) {
  36457. activeTextures.push(this._microSurfaceTexture);
  36458. }
  36459. if (this._bumpTexture) {
  36460. activeTextures.push(this._bumpTexture);
  36461. }
  36462. if (this._lightmapTexture) {
  36463. activeTextures.push(this._lightmapTexture);
  36464. }
  36465. if (this._refractionTexture) {
  36466. activeTextures.push(this._refractionTexture);
  36467. }
  36468. return activeTextures;
  36469. };
  36470. PBRMaterial.prototype.hasTexture = function (texture) {
  36471. if (_super.prototype.hasTexture.call(this, texture)) {
  36472. return true;
  36473. }
  36474. if (this._albedoTexture === texture) {
  36475. return true;
  36476. }
  36477. if (this._ambientTexture === texture) {
  36478. return true;
  36479. }
  36480. if (this._opacityTexture === texture) {
  36481. return true;
  36482. }
  36483. if (this._reflectionTexture === texture) {
  36484. return true;
  36485. }
  36486. if (this._reflectivityTexture === texture) {
  36487. return true;
  36488. }
  36489. if (this._metallicTexture === texture) {
  36490. return true;
  36491. }
  36492. if (this._microSurfaceTexture === texture) {
  36493. return true;
  36494. }
  36495. if (this._bumpTexture === texture) {
  36496. return true;
  36497. }
  36498. if (this._lightmapTexture === texture) {
  36499. return true;
  36500. }
  36501. if (this._refractionTexture === texture) {
  36502. return true;
  36503. }
  36504. return false;
  36505. };
  36506. PBRMaterial.prototype.clone = function (name) {
  36507. var _this = this;
  36508. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36509. clone.id = name;
  36510. clone.name = name;
  36511. return clone;
  36512. };
  36513. PBRMaterial.prototype.serialize = function () {
  36514. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36515. serializationObject.customType = "BABYLON.PBRMaterial";
  36516. return serializationObject;
  36517. };
  36518. // Statics
  36519. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36520. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36521. };
  36522. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36523. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36524. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36525. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36526. __decorate([
  36527. BABYLON.serialize(),
  36528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36529. ], PBRMaterial.prototype, "directIntensity", void 0);
  36530. __decorate([
  36531. BABYLON.serialize(),
  36532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36533. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36534. __decorate([
  36535. BABYLON.serialize(),
  36536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36537. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36538. __decorate([
  36539. BABYLON.serialize(),
  36540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36541. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36542. __decorate([
  36543. BABYLON.serialize(),
  36544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36545. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36546. __decorate([
  36547. BABYLON.serializeAsTexture(),
  36548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36549. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36550. __decorate([
  36551. BABYLON.serializeAsTexture(),
  36552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36553. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36554. __decorate([
  36555. BABYLON.serialize(),
  36556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36557. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36558. __decorate([
  36559. BABYLON.serializeAsTexture(),
  36560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36561. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36562. __decorate([
  36563. BABYLON.serializeAsTexture(),
  36564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36565. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36566. __decorate([
  36567. BABYLON.serializeAsTexture(),
  36568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36569. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36570. __decorate([
  36571. BABYLON.serializeAsTexture(),
  36572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36573. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36574. __decorate([
  36575. BABYLON.serializeAsTexture(),
  36576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36577. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36578. __decorate([
  36579. BABYLON.serialize(),
  36580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36581. ], PBRMaterial.prototype, "metallic", void 0);
  36582. __decorate([
  36583. BABYLON.serialize(),
  36584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36585. ], PBRMaterial.prototype, "roughness", void 0);
  36586. __decorate([
  36587. BABYLON.serializeAsTexture(),
  36588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36589. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36590. __decorate([
  36591. BABYLON.serializeAsTexture(),
  36592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36593. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36594. __decorate([
  36595. BABYLON.serializeAsTexture(),
  36596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36597. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36598. __decorate([
  36599. BABYLON.serializeAsTexture(),
  36600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36601. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36602. __decorate([
  36603. BABYLON.serializeAsColor3("ambient"),
  36604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36605. ], PBRMaterial.prototype, "ambientColor", void 0);
  36606. __decorate([
  36607. BABYLON.serializeAsColor3("albedo"),
  36608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36609. ], PBRMaterial.prototype, "albedoColor", void 0);
  36610. __decorate([
  36611. BABYLON.serializeAsColor3("reflectivity"),
  36612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36613. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36614. __decorate([
  36615. BABYLON.serializeAsColor3("reflection"),
  36616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36617. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36618. __decorate([
  36619. BABYLON.serializeAsColor3("emissive"),
  36620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36621. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36622. __decorate([
  36623. BABYLON.serialize(),
  36624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36625. ], PBRMaterial.prototype, "microSurface", void 0);
  36626. __decorate([
  36627. BABYLON.serialize(),
  36628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36629. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36630. __decorate([
  36631. BABYLON.serialize(),
  36632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36633. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36634. __decorate([
  36635. BABYLON.serialize(),
  36636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36637. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36638. __decorate([
  36639. BABYLON.serialize(),
  36640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36641. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36642. __decorate([
  36643. BABYLON.serialize(),
  36644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36645. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36646. __decorate([
  36647. BABYLON.serialize(),
  36648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36649. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36650. __decorate([
  36651. BABYLON.serialize(),
  36652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36653. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36654. __decorate([
  36655. BABYLON.serialize(),
  36656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36657. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36658. __decorate([
  36659. BABYLON.serialize(),
  36660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36661. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36662. __decorate([
  36663. BABYLON.serialize(),
  36664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36665. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36666. __decorate([
  36667. BABYLON.serialize(),
  36668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36669. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36670. __decorate([
  36671. BABYLON.serialize(),
  36672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36673. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36674. __decorate([
  36675. BABYLON.serialize(),
  36676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36677. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36678. __decorate([
  36679. BABYLON.serialize(),
  36680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36681. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36682. __decorate([
  36683. BABYLON.serialize(),
  36684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36685. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36686. __decorate([
  36687. BABYLON.serialize(),
  36688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36689. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36690. __decorate([
  36691. BABYLON.serialize(),
  36692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36693. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36694. __decorate([
  36695. BABYLON.serialize(),
  36696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36697. ], PBRMaterial.prototype, "useParallax", void 0);
  36698. __decorate([
  36699. BABYLON.serialize(),
  36700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36701. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36702. __decorate([
  36703. BABYLON.serialize(),
  36704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36705. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36706. __decorate([
  36707. BABYLON.serialize(),
  36708. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36709. ], PBRMaterial.prototype, "disableLighting", void 0);
  36710. __decorate([
  36711. BABYLON.serialize(),
  36712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36713. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36714. __decorate([
  36715. BABYLON.serialize(),
  36716. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36717. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36718. __decorate([
  36719. BABYLON.serialize(),
  36720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36721. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36722. __decorate([
  36723. BABYLON.serialize(),
  36724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36725. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36726. __decorate([
  36727. BABYLON.serialize(),
  36728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36729. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36730. __decorate([
  36731. BABYLON.serialize(),
  36732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36733. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36734. __decorate([
  36735. BABYLON.serializeAsTexture(),
  36736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36737. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36738. __decorate([
  36739. BABYLON.serialize(),
  36740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36741. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36742. return PBRMaterial;
  36743. }(BABYLON.PBRBaseMaterial));
  36744. BABYLON.PBRMaterial = PBRMaterial;
  36745. })(BABYLON || (BABYLON = {}));
  36746. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36747. var BABYLON;
  36748. (function (BABYLON) {
  36749. /**
  36750. * The PBR material of BJS following the metal roughness convention.
  36751. *
  36752. * This fits to the PBR convention in the GLTF definition:
  36753. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36754. */
  36755. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36756. __extends(PBRMetallicRoughnessMaterial, _super);
  36757. /**
  36758. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36759. *
  36760. * @param name The material name
  36761. * @param scene The scene the material will be use in.
  36762. */
  36763. function PBRMetallicRoughnessMaterial(name, scene) {
  36764. var _this = _super.call(this, name, scene) || this;
  36765. _this._useRoughnessFromMetallicTextureAlpha = false;
  36766. _this._useRoughnessFromMetallicTextureGreen = true;
  36767. _this._useMetallnessFromMetallicTextureBlue = true;
  36768. return _this;
  36769. }
  36770. /**
  36771. * Return the currrent class name of the material.
  36772. */
  36773. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36774. return "PBRMetallicRoughnessMaterial";
  36775. };
  36776. /**
  36777. * Return the active textures of the material.
  36778. */
  36779. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36780. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36781. if (this.baseTexture) {
  36782. activeTextures.push(this.baseTexture);
  36783. }
  36784. if (this.metallicRoughnessTexture) {
  36785. activeTextures.push(this.metallicRoughnessTexture);
  36786. }
  36787. return activeTextures;
  36788. };
  36789. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36790. if (_super.prototype.hasTexture.call(this, texture)) {
  36791. return true;
  36792. }
  36793. if (this.baseTexture === texture) {
  36794. return true;
  36795. }
  36796. if (this.metallicRoughnessTexture === texture) {
  36797. return true;
  36798. }
  36799. return false;
  36800. };
  36801. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36802. var _this = this;
  36803. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36804. clone.id = name;
  36805. clone.name = name;
  36806. return clone;
  36807. };
  36808. /**
  36809. * Serialize the material to a parsable JSON object.
  36810. */
  36811. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36812. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36813. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36814. return serializationObject;
  36815. };
  36816. /**
  36817. * Parses a JSON object correponding to the serialize function.
  36818. */
  36819. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36820. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36821. };
  36822. __decorate([
  36823. BABYLON.serializeAsColor3(),
  36824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36825. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36826. __decorate([
  36827. BABYLON.serializeAsTexture(),
  36828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36829. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36830. __decorate([
  36831. BABYLON.serialize(),
  36832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36833. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36834. __decorate([
  36835. BABYLON.serialize(),
  36836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36837. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36838. __decorate([
  36839. BABYLON.serializeAsTexture(),
  36840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36841. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36842. return PBRMetallicRoughnessMaterial;
  36843. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36844. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36845. })(BABYLON || (BABYLON = {}));
  36846. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36847. var BABYLON;
  36848. (function (BABYLON) {
  36849. /**
  36850. * The PBR material of BJS following the specular glossiness convention.
  36851. *
  36852. * This fits to the PBR convention in the GLTF definition:
  36853. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36854. */
  36855. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36856. __extends(PBRSpecularGlossinessMaterial, _super);
  36857. /**
  36858. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36859. *
  36860. * @param name The material name
  36861. * @param scene The scene the material will be use in.
  36862. */
  36863. function PBRSpecularGlossinessMaterial(name, scene) {
  36864. var _this = _super.call(this, name, scene) || this;
  36865. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36866. return _this;
  36867. }
  36868. /**
  36869. * Return the currrent class name of the material.
  36870. */
  36871. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36872. return "PBRSpecularGlossinessMaterial";
  36873. };
  36874. /**
  36875. * Return the active textures of the material.
  36876. */
  36877. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36878. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36879. if (this.diffuseTexture) {
  36880. activeTextures.push(this.diffuseTexture);
  36881. }
  36882. if (this.specularGlossinessTexture) {
  36883. activeTextures.push(this.specularGlossinessTexture);
  36884. }
  36885. return activeTextures;
  36886. };
  36887. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36888. if (_super.prototype.hasTexture.call(this, texture)) {
  36889. return true;
  36890. }
  36891. if (this.diffuseTexture === texture) {
  36892. return true;
  36893. }
  36894. if (this.specularGlossinessTexture === texture) {
  36895. return true;
  36896. }
  36897. return false;
  36898. };
  36899. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36900. var _this = this;
  36901. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36902. clone.id = name;
  36903. clone.name = name;
  36904. return clone;
  36905. };
  36906. /**
  36907. * Serialize the material to a parsable JSON object.
  36908. */
  36909. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36910. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36911. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36912. return serializationObject;
  36913. };
  36914. /**
  36915. * Parses a JSON object correponding to the serialize function.
  36916. */
  36917. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36918. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36919. };
  36920. __decorate([
  36921. BABYLON.serializeAsColor3("diffuse"),
  36922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36923. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36924. __decorate([
  36925. BABYLON.serializeAsTexture(),
  36926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36927. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36928. __decorate([
  36929. BABYLON.serializeAsColor3("specular"),
  36930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36931. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36932. __decorate([
  36933. BABYLON.serialize(),
  36934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36935. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36936. __decorate([
  36937. BABYLON.serializeAsTexture(),
  36938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36939. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36940. return PBRSpecularGlossinessMaterial;
  36941. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36942. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36943. })(BABYLON || (BABYLON = {}));
  36944. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36945. var BABYLON;
  36946. (function (BABYLON) {
  36947. BABYLON.CameraInputTypes = {};
  36948. var CameraInputsManager = /** @class */ (function () {
  36949. function CameraInputsManager(camera) {
  36950. this.attached = {};
  36951. this.camera = camera;
  36952. this.checkInputs = function () { };
  36953. }
  36954. CameraInputsManager.prototype.add = function (input) {
  36955. var type = input.getSimpleName();
  36956. if (this.attached[type]) {
  36957. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36958. return;
  36959. }
  36960. this.attached[type] = input;
  36961. input.camera = this.camera;
  36962. //for checkInputs, we are dynamically creating a function
  36963. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36964. if (input.checkInputs) {
  36965. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36966. }
  36967. if (this.attachedElement) {
  36968. input.attachControl(this.attachedElement);
  36969. }
  36970. };
  36971. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36972. for (var cam in this.attached) {
  36973. var input = this.attached[cam];
  36974. if (input === inputToRemove) {
  36975. input.detachControl(this.attachedElement);
  36976. input.camera = null;
  36977. delete this.attached[cam];
  36978. this.rebuildInputCheck();
  36979. }
  36980. }
  36981. };
  36982. CameraInputsManager.prototype.removeByType = function (inputType) {
  36983. for (var cam in this.attached) {
  36984. var input = this.attached[cam];
  36985. if (input.getClassName() === inputType) {
  36986. input.detachControl(this.attachedElement);
  36987. input.camera = null;
  36988. delete this.attached[cam];
  36989. this.rebuildInputCheck();
  36990. }
  36991. }
  36992. };
  36993. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36994. var current = this.checkInputs;
  36995. return function () {
  36996. current();
  36997. fn();
  36998. };
  36999. };
  37000. CameraInputsManager.prototype.attachInput = function (input) {
  37001. if (this.attachedElement) {
  37002. input.attachControl(this.attachedElement, this.noPreventDefault);
  37003. }
  37004. };
  37005. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37006. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37007. if (this.attachedElement) {
  37008. return;
  37009. }
  37010. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37011. this.attachedElement = element;
  37012. this.noPreventDefault = noPreventDefault;
  37013. for (var cam in this.attached) {
  37014. this.attached[cam].attachControl(element, noPreventDefault);
  37015. }
  37016. };
  37017. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37018. if (disconnect === void 0) { disconnect = false; }
  37019. if (this.attachedElement !== element) {
  37020. return;
  37021. }
  37022. for (var cam in this.attached) {
  37023. this.attached[cam].detachControl(element);
  37024. if (disconnect) {
  37025. this.attached[cam].camera = null;
  37026. }
  37027. }
  37028. this.attachedElement = null;
  37029. };
  37030. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37031. this.checkInputs = function () { };
  37032. for (var cam in this.attached) {
  37033. var input = this.attached[cam];
  37034. if (input.checkInputs) {
  37035. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37036. }
  37037. }
  37038. };
  37039. CameraInputsManager.prototype.clear = function () {
  37040. if (this.attachedElement) {
  37041. this.detachElement(this.attachedElement, true);
  37042. }
  37043. this.attached = {};
  37044. this.attachedElement = null;
  37045. this.checkInputs = function () { };
  37046. };
  37047. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37048. var inputs = {};
  37049. for (var cam in this.attached) {
  37050. var input = this.attached[cam];
  37051. var res = BABYLON.SerializationHelper.Serialize(input);
  37052. inputs[input.getClassName()] = res;
  37053. }
  37054. serializedCamera.inputsmgr = inputs;
  37055. };
  37056. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37057. var parsedInputs = parsedCamera.inputsmgr;
  37058. if (parsedInputs) {
  37059. this.clear();
  37060. for (var n in parsedInputs) {
  37061. var construct = BABYLON.CameraInputTypes[n];
  37062. if (construct) {
  37063. var parsedinput = parsedInputs[n];
  37064. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37065. this.add(input);
  37066. }
  37067. }
  37068. }
  37069. else {
  37070. //2016-03-08 this part is for managing backward compatibility
  37071. for (var n in this.attached) {
  37072. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37073. if (construct) {
  37074. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37075. this.remove(this.attached[n]);
  37076. this.add(input);
  37077. }
  37078. }
  37079. }
  37080. };
  37081. return CameraInputsManager;
  37082. }());
  37083. BABYLON.CameraInputsManager = CameraInputsManager;
  37084. })(BABYLON || (BABYLON = {}));
  37085. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37086. var BABYLON;
  37087. (function (BABYLON) {
  37088. var FreeCameraMouseInput = /** @class */ (function () {
  37089. function FreeCameraMouseInput(touchEnabled) {
  37090. if (touchEnabled === void 0) { touchEnabled = true; }
  37091. this.touchEnabled = touchEnabled;
  37092. this.buttons = [0, 1, 2];
  37093. this.angularSensibility = 2000.0;
  37094. this.previousPosition = null;
  37095. }
  37096. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37097. var _this = this;
  37098. var engine = this.camera.getEngine();
  37099. if (!this._pointerInput) {
  37100. this._pointerInput = function (p, s) {
  37101. var evt = p.event;
  37102. if (engine.isInVRExclusivePointerMode) {
  37103. return;
  37104. }
  37105. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37106. return;
  37107. }
  37108. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37109. return;
  37110. }
  37111. var srcElement = (evt.srcElement || evt.target);
  37112. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37113. try {
  37114. srcElement.setPointerCapture(evt.pointerId);
  37115. }
  37116. catch (e) {
  37117. //Nothing to do with the error. Execution will continue.
  37118. }
  37119. _this.previousPosition = {
  37120. x: evt.clientX,
  37121. y: evt.clientY
  37122. };
  37123. if (!noPreventDefault) {
  37124. evt.preventDefault();
  37125. element.focus();
  37126. }
  37127. }
  37128. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37129. try {
  37130. srcElement.releasePointerCapture(evt.pointerId);
  37131. }
  37132. catch (e) {
  37133. //Nothing to do with the error.
  37134. }
  37135. _this.previousPosition = null;
  37136. if (!noPreventDefault) {
  37137. evt.preventDefault();
  37138. }
  37139. }
  37140. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37141. if (!_this.previousPosition || engine.isPointerLock) {
  37142. return;
  37143. }
  37144. var offsetX = evt.clientX - _this.previousPosition.x;
  37145. var offsetY = evt.clientY - _this.previousPosition.y;
  37146. if (_this.camera.getScene().useRightHandedSystem) {
  37147. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37148. }
  37149. else {
  37150. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37151. }
  37152. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37153. _this.previousPosition = {
  37154. x: evt.clientX,
  37155. y: evt.clientY
  37156. };
  37157. if (!noPreventDefault) {
  37158. evt.preventDefault();
  37159. }
  37160. }
  37161. };
  37162. }
  37163. this._onMouseMove = function (evt) {
  37164. if (!engine.isPointerLock) {
  37165. return;
  37166. }
  37167. if (engine.isInVRExclusivePointerMode) {
  37168. return;
  37169. }
  37170. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37171. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37172. if (_this.camera.getScene().useRightHandedSystem) {
  37173. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37174. }
  37175. else {
  37176. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37177. }
  37178. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37179. _this.previousPosition = null;
  37180. if (!noPreventDefault) {
  37181. evt.preventDefault();
  37182. }
  37183. };
  37184. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37185. element.addEventListener("mousemove", this._onMouseMove, false);
  37186. };
  37187. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37188. if (this._observer && element) {
  37189. this.camera.getScene().onPointerObservable.remove(this._observer);
  37190. if (this._onMouseMove) {
  37191. element.removeEventListener("mousemove", this._onMouseMove);
  37192. }
  37193. this._observer = null;
  37194. this._onMouseMove = null;
  37195. this.previousPosition = null;
  37196. }
  37197. };
  37198. FreeCameraMouseInput.prototype.getClassName = function () {
  37199. return "FreeCameraMouseInput";
  37200. };
  37201. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37202. return "mouse";
  37203. };
  37204. __decorate([
  37205. BABYLON.serialize()
  37206. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37207. __decorate([
  37208. BABYLON.serialize()
  37209. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37210. return FreeCameraMouseInput;
  37211. }());
  37212. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37213. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37214. })(BABYLON || (BABYLON = {}));
  37215. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37216. var BABYLON;
  37217. (function (BABYLON) {
  37218. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37219. function FreeCameraKeyboardMoveInput() {
  37220. this._keys = new Array();
  37221. this.keysUp = [38];
  37222. this.keysDown = [40];
  37223. this.keysLeft = [37];
  37224. this.keysRight = [39];
  37225. }
  37226. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37227. var _this = this;
  37228. if (this._onCanvasBlurObserver) {
  37229. return;
  37230. }
  37231. this._scene = this.camera.getScene();
  37232. this._engine = this._scene.getEngine();
  37233. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37234. _this._keys = [];
  37235. });
  37236. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37237. var evt = info.event;
  37238. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37239. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37240. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37241. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37242. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37243. var index = _this._keys.indexOf(evt.keyCode);
  37244. if (index === -1) {
  37245. _this._keys.push(evt.keyCode);
  37246. }
  37247. if (!noPreventDefault) {
  37248. evt.preventDefault();
  37249. }
  37250. }
  37251. }
  37252. else {
  37253. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37254. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37255. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37256. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37257. var index = _this._keys.indexOf(evt.keyCode);
  37258. if (index >= 0) {
  37259. _this._keys.splice(index, 1);
  37260. }
  37261. if (!noPreventDefault) {
  37262. evt.preventDefault();
  37263. }
  37264. }
  37265. }
  37266. });
  37267. };
  37268. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37269. if (this._scene) {
  37270. if (this._onKeyboardObserver) {
  37271. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37272. }
  37273. if (this._onCanvasBlurObserver) {
  37274. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37275. }
  37276. this._onKeyboardObserver = null;
  37277. this._onCanvasBlurObserver = null;
  37278. }
  37279. this._keys = [];
  37280. };
  37281. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37282. if (this._onKeyboardObserver) {
  37283. var camera = this.camera;
  37284. // Keyboard
  37285. for (var index = 0; index < this._keys.length; index++) {
  37286. var keyCode = this._keys[index];
  37287. var speed = camera._computeLocalCameraSpeed();
  37288. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37289. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37290. }
  37291. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37292. camera._localDirection.copyFromFloats(0, 0, speed);
  37293. }
  37294. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37295. camera._localDirection.copyFromFloats(speed, 0, 0);
  37296. }
  37297. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37298. camera._localDirection.copyFromFloats(0, 0, -speed);
  37299. }
  37300. if (camera.getScene().useRightHandedSystem) {
  37301. camera._localDirection.z *= -1;
  37302. }
  37303. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37304. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37305. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37306. }
  37307. }
  37308. };
  37309. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37310. return "FreeCameraKeyboardMoveInput";
  37311. };
  37312. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37313. this._keys = [];
  37314. };
  37315. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37316. return "keyboard";
  37317. };
  37318. __decorate([
  37319. BABYLON.serialize()
  37320. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37321. __decorate([
  37322. BABYLON.serialize()
  37323. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37324. __decorate([
  37325. BABYLON.serialize()
  37326. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37327. __decorate([
  37328. BABYLON.serialize()
  37329. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37330. return FreeCameraKeyboardMoveInput;
  37331. }());
  37332. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37333. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37334. })(BABYLON || (BABYLON = {}));
  37335. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37336. var BABYLON;
  37337. (function (BABYLON) {
  37338. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37339. __extends(FreeCameraInputsManager, _super);
  37340. function FreeCameraInputsManager(camera) {
  37341. return _super.call(this, camera) || this;
  37342. }
  37343. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37344. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37345. return this;
  37346. };
  37347. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37348. if (touchEnabled === void 0) { touchEnabled = true; }
  37349. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37350. return this;
  37351. };
  37352. FreeCameraInputsManager.prototype.addGamepad = function () {
  37353. this.add(new BABYLON.FreeCameraGamepadInput());
  37354. return this;
  37355. };
  37356. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37357. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37358. return this;
  37359. };
  37360. FreeCameraInputsManager.prototype.addTouch = function () {
  37361. this.add(new BABYLON.FreeCameraTouchInput());
  37362. return this;
  37363. };
  37364. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37365. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37366. return this;
  37367. };
  37368. return FreeCameraInputsManager;
  37369. }(BABYLON.CameraInputsManager));
  37370. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37371. })(BABYLON || (BABYLON = {}));
  37372. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37373. var BABYLON;
  37374. (function (BABYLON) {
  37375. var TargetCamera = /** @class */ (function (_super) {
  37376. __extends(TargetCamera, _super);
  37377. function TargetCamera(name, position, scene) {
  37378. var _this = _super.call(this, name, position, scene) || this;
  37379. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37380. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37381. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37382. _this.speed = 2.0;
  37383. _this.noRotationConstraint = false;
  37384. _this.lockedTarget = null;
  37385. _this._currentTarget = BABYLON.Vector3.Zero();
  37386. _this._viewMatrix = BABYLON.Matrix.Zero();
  37387. _this._camMatrix = BABYLON.Matrix.Zero();
  37388. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37389. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37390. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37391. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37392. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37393. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37394. _this._tempMatrix = BABYLON.Matrix.Zero();
  37395. return _this;
  37396. }
  37397. TargetCamera.prototype.getFrontPosition = function (distance) {
  37398. var direction = this.getTarget().subtract(this.position);
  37399. direction.normalize();
  37400. direction.scaleInPlace(distance);
  37401. return this.globalPosition.add(direction);
  37402. };
  37403. TargetCamera.prototype._getLockedTargetPosition = function () {
  37404. if (!this.lockedTarget) {
  37405. return null;
  37406. }
  37407. if (this.lockedTarget.absolutePosition) {
  37408. this.lockedTarget.computeWorldMatrix();
  37409. }
  37410. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37411. };
  37412. TargetCamera.prototype.storeState = function () {
  37413. this._storedPosition = this.position.clone();
  37414. this._storedRotation = this.rotation.clone();
  37415. if (this.rotationQuaternion) {
  37416. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37417. }
  37418. return _super.prototype.storeState.call(this);
  37419. };
  37420. /**
  37421. * Restored camera state. You must call storeState() first
  37422. */
  37423. TargetCamera.prototype._restoreStateValues = function () {
  37424. if (!_super.prototype._restoreStateValues.call(this)) {
  37425. return false;
  37426. }
  37427. this.position = this._storedPosition.clone();
  37428. this.rotation = this._storedRotation.clone();
  37429. if (this.rotationQuaternion) {
  37430. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37431. }
  37432. this.cameraDirection.copyFromFloats(0, 0, 0);
  37433. this.cameraRotation.copyFromFloats(0, 0);
  37434. return true;
  37435. };
  37436. // Cache
  37437. TargetCamera.prototype._initCache = function () {
  37438. _super.prototype._initCache.call(this);
  37439. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37440. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37441. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37442. };
  37443. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37444. if (!ignoreParentClass) {
  37445. _super.prototype._updateCache.call(this);
  37446. }
  37447. var lockedTargetPosition = this._getLockedTargetPosition();
  37448. if (!lockedTargetPosition) {
  37449. this._cache.lockedTarget = null;
  37450. }
  37451. else {
  37452. if (!this._cache.lockedTarget) {
  37453. this._cache.lockedTarget = lockedTargetPosition.clone();
  37454. }
  37455. else {
  37456. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37457. }
  37458. }
  37459. this._cache.rotation.copyFrom(this.rotation);
  37460. if (this.rotationQuaternion)
  37461. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37462. };
  37463. // Synchronized
  37464. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37465. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37466. return false;
  37467. }
  37468. var lockedTargetPosition = this._getLockedTargetPosition();
  37469. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37470. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37471. };
  37472. // Methods
  37473. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37474. var engine = this.getEngine();
  37475. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37476. };
  37477. // Target
  37478. TargetCamera.prototype.setTarget = function (target) {
  37479. this.upVector.normalize();
  37480. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37481. this._camMatrix.invert();
  37482. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37483. var vDir = target.subtract(this.position);
  37484. if (vDir.x >= 0.0) {
  37485. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37486. }
  37487. else {
  37488. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37489. }
  37490. this.rotation.z = 0;
  37491. if (isNaN(this.rotation.x)) {
  37492. this.rotation.x = 0;
  37493. }
  37494. if (isNaN(this.rotation.y)) {
  37495. this.rotation.y = 0;
  37496. }
  37497. if (isNaN(this.rotation.z)) {
  37498. this.rotation.z = 0;
  37499. }
  37500. if (this.rotationQuaternion) {
  37501. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37502. }
  37503. };
  37504. /**
  37505. * Return the current target position of the camera. This value is expressed in local space.
  37506. */
  37507. TargetCamera.prototype.getTarget = function () {
  37508. return this._currentTarget;
  37509. };
  37510. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37511. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37512. };
  37513. TargetCamera.prototype._updatePosition = function () {
  37514. if (this.parent) {
  37515. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37516. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37517. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37518. return;
  37519. }
  37520. this.position.addInPlace(this.cameraDirection);
  37521. };
  37522. TargetCamera.prototype._checkInputs = function () {
  37523. var needToMove = this._decideIfNeedsToMove();
  37524. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37525. // Move
  37526. if (needToMove) {
  37527. this._updatePosition();
  37528. }
  37529. // Rotate
  37530. if (needToRotate) {
  37531. this.rotation.x += this.cameraRotation.x;
  37532. this.rotation.y += this.cameraRotation.y;
  37533. //rotate, if quaternion is set and rotation was used
  37534. if (this.rotationQuaternion) {
  37535. var len = this.rotation.lengthSquared();
  37536. if (len) {
  37537. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37538. }
  37539. }
  37540. if (!this.noRotationConstraint) {
  37541. var limit = (Math.PI / 2) * 0.95;
  37542. if (this.rotation.x > limit)
  37543. this.rotation.x = limit;
  37544. if (this.rotation.x < -limit)
  37545. this.rotation.x = -limit;
  37546. }
  37547. }
  37548. // Inertia
  37549. if (needToMove) {
  37550. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37551. this.cameraDirection.x = 0;
  37552. }
  37553. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37554. this.cameraDirection.y = 0;
  37555. }
  37556. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37557. this.cameraDirection.z = 0;
  37558. }
  37559. this.cameraDirection.scaleInPlace(this.inertia);
  37560. }
  37561. if (needToRotate) {
  37562. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37563. this.cameraRotation.x = 0;
  37564. }
  37565. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37566. this.cameraRotation.y = 0;
  37567. }
  37568. this.cameraRotation.scaleInPlace(this.inertia);
  37569. }
  37570. _super.prototype._checkInputs.call(this);
  37571. };
  37572. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37573. if (this.rotationQuaternion) {
  37574. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37575. }
  37576. else {
  37577. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37578. }
  37579. //update the up vector!
  37580. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37581. };
  37582. TargetCamera.prototype._getViewMatrix = function () {
  37583. if (!this.lockedTarget) {
  37584. // Compute
  37585. this._updateCameraRotationMatrix();
  37586. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37587. // Computing target and final matrix
  37588. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37589. }
  37590. else {
  37591. var targetPosition = this._getLockedTargetPosition();
  37592. if (targetPosition) {
  37593. this._currentTarget.copyFrom(targetPosition);
  37594. }
  37595. }
  37596. if (this.getScene().useRightHandedSystem) {
  37597. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37598. }
  37599. else {
  37600. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37601. }
  37602. return this._viewMatrix;
  37603. };
  37604. /**
  37605. * @override
  37606. * Override Camera.createRigCamera
  37607. */
  37608. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37609. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37610. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37611. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37612. if (!this.rotationQuaternion) {
  37613. this.rotationQuaternion = new BABYLON.Quaternion();
  37614. }
  37615. rigCamera._cameraRigParams = {};
  37616. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37617. }
  37618. return rigCamera;
  37619. }
  37620. return null;
  37621. };
  37622. /**
  37623. * @override
  37624. * Override Camera._updateRigCameras
  37625. */
  37626. TargetCamera.prototype._updateRigCameras = function () {
  37627. var camLeft = this._rigCameras[0];
  37628. var camRight = this._rigCameras[1];
  37629. switch (this.cameraRigMode) {
  37630. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37631. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37632. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37634. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37635. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37636. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37637. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37638. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37639. camLeft.setTarget(this.getTarget());
  37640. camRight.setTarget(this.getTarget());
  37641. break;
  37642. case BABYLON.Camera.RIG_MODE_VR:
  37643. if (camLeft.rotationQuaternion) {
  37644. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37645. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37646. }
  37647. else {
  37648. camLeft.rotation.copyFrom(this.rotation);
  37649. camRight.rotation.copyFrom(this.rotation);
  37650. }
  37651. camLeft.position.copyFrom(this.position);
  37652. camRight.position.copyFrom(this.position);
  37653. break;
  37654. }
  37655. _super.prototype._updateRigCameras.call(this);
  37656. };
  37657. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37658. if (!this._rigCamTransformMatrix) {
  37659. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37660. }
  37661. var target = this.getTarget();
  37662. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37663. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37664. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37665. };
  37666. TargetCamera.prototype.getClassName = function () {
  37667. return "TargetCamera";
  37668. };
  37669. __decorate([
  37670. BABYLON.serializeAsVector3()
  37671. ], TargetCamera.prototype, "rotation", void 0);
  37672. __decorate([
  37673. BABYLON.serialize()
  37674. ], TargetCamera.prototype, "speed", void 0);
  37675. __decorate([
  37676. BABYLON.serializeAsMeshReference("lockedTargetId")
  37677. ], TargetCamera.prototype, "lockedTarget", void 0);
  37678. return TargetCamera;
  37679. }(BABYLON.Camera));
  37680. BABYLON.TargetCamera = TargetCamera;
  37681. })(BABYLON || (BABYLON = {}));
  37682. //# sourceMappingURL=babylon.targetCamera.js.map
  37683. var BABYLON;
  37684. (function (BABYLON) {
  37685. var FreeCamera = /** @class */ (function (_super) {
  37686. __extends(FreeCamera, _super);
  37687. function FreeCamera(name, position, scene) {
  37688. var _this = _super.call(this, name, position, scene) || this;
  37689. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37690. _this.checkCollisions = false;
  37691. _this.applyGravity = false;
  37692. _this._needMoveForGravity = false;
  37693. _this._oldPosition = BABYLON.Vector3.Zero();
  37694. _this._diffPosition = BABYLON.Vector3.Zero();
  37695. _this._newPosition = BABYLON.Vector3.Zero();
  37696. // Collisions
  37697. _this._collisionMask = -1;
  37698. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37699. if (collidedMesh === void 0) { collidedMesh = null; }
  37700. //TODO move this to the collision coordinator!
  37701. if (_this.getScene().workerCollisions)
  37702. newPosition.multiplyInPlace(_this._collider.radius);
  37703. var updatePosition = function (newPos) {
  37704. _this._newPosition.copyFrom(newPos);
  37705. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37706. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37707. _this.position.addInPlace(_this._diffPosition);
  37708. if (_this.onCollide && collidedMesh) {
  37709. _this.onCollide(collidedMesh);
  37710. }
  37711. }
  37712. };
  37713. updatePosition(newPosition);
  37714. };
  37715. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37716. _this.inputs.addKeyboard().addMouse();
  37717. return _this;
  37718. }
  37719. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37720. //-- begin properties for backward compatibility for inputs
  37721. get: function () {
  37722. var mouse = this.inputs.attached["mouse"];
  37723. if (mouse)
  37724. return mouse.angularSensibility;
  37725. return 0;
  37726. },
  37727. set: function (value) {
  37728. var mouse = this.inputs.attached["mouse"];
  37729. if (mouse)
  37730. mouse.angularSensibility = value;
  37731. },
  37732. enumerable: true,
  37733. configurable: true
  37734. });
  37735. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37736. get: function () {
  37737. var keyboard = this.inputs.attached["keyboard"];
  37738. if (keyboard)
  37739. return keyboard.keysUp;
  37740. return [];
  37741. },
  37742. set: function (value) {
  37743. var keyboard = this.inputs.attached["keyboard"];
  37744. if (keyboard)
  37745. keyboard.keysUp = value;
  37746. },
  37747. enumerable: true,
  37748. configurable: true
  37749. });
  37750. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37751. get: function () {
  37752. var keyboard = this.inputs.attached["keyboard"];
  37753. if (keyboard)
  37754. return keyboard.keysDown;
  37755. return [];
  37756. },
  37757. set: function (value) {
  37758. var keyboard = this.inputs.attached["keyboard"];
  37759. if (keyboard)
  37760. keyboard.keysDown = value;
  37761. },
  37762. enumerable: true,
  37763. configurable: true
  37764. });
  37765. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37766. get: function () {
  37767. var keyboard = this.inputs.attached["keyboard"];
  37768. if (keyboard)
  37769. return keyboard.keysLeft;
  37770. return [];
  37771. },
  37772. set: function (value) {
  37773. var keyboard = this.inputs.attached["keyboard"];
  37774. if (keyboard)
  37775. keyboard.keysLeft = value;
  37776. },
  37777. enumerable: true,
  37778. configurable: true
  37779. });
  37780. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37781. get: function () {
  37782. var keyboard = this.inputs.attached["keyboard"];
  37783. if (keyboard)
  37784. return keyboard.keysRight;
  37785. return [];
  37786. },
  37787. set: function (value) {
  37788. var keyboard = this.inputs.attached["keyboard"];
  37789. if (keyboard)
  37790. keyboard.keysRight = value;
  37791. },
  37792. enumerable: true,
  37793. configurable: true
  37794. });
  37795. // Controls
  37796. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37797. this.inputs.attachElement(element, noPreventDefault);
  37798. };
  37799. FreeCamera.prototype.detachControl = function (element) {
  37800. this.inputs.detachElement(element);
  37801. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37802. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37803. };
  37804. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37805. get: function () {
  37806. return this._collisionMask;
  37807. },
  37808. set: function (mask) {
  37809. this._collisionMask = !isNaN(mask) ? mask : -1;
  37810. },
  37811. enumerable: true,
  37812. configurable: true
  37813. });
  37814. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37815. var globalPosition;
  37816. if (this.parent) {
  37817. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37818. }
  37819. else {
  37820. globalPosition = this.position;
  37821. }
  37822. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37823. if (!this._collider) {
  37824. this._collider = new BABYLON.Collider();
  37825. }
  37826. this._collider.radius = this.ellipsoid;
  37827. this._collider.collisionMask = this._collisionMask;
  37828. //no need for clone, as long as gravity is not on.
  37829. var actualDisplacement = displacement;
  37830. //add gravity to the direction to prevent the dual-collision checking
  37831. if (this.applyGravity) {
  37832. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37833. actualDisplacement = displacement.add(this.getScene().gravity);
  37834. }
  37835. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37836. };
  37837. FreeCamera.prototype._checkInputs = function () {
  37838. if (!this._localDirection) {
  37839. this._localDirection = BABYLON.Vector3.Zero();
  37840. this._transformedDirection = BABYLON.Vector3.Zero();
  37841. }
  37842. this.inputs.checkInputs();
  37843. _super.prototype._checkInputs.call(this);
  37844. };
  37845. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37846. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37847. };
  37848. FreeCamera.prototype._updatePosition = function () {
  37849. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37850. this._collideWithWorld(this.cameraDirection);
  37851. }
  37852. else {
  37853. _super.prototype._updatePosition.call(this);
  37854. }
  37855. };
  37856. FreeCamera.prototype.dispose = function () {
  37857. this.inputs.clear();
  37858. _super.prototype.dispose.call(this);
  37859. };
  37860. FreeCamera.prototype.getClassName = function () {
  37861. return "FreeCamera";
  37862. };
  37863. __decorate([
  37864. BABYLON.serializeAsVector3()
  37865. ], FreeCamera.prototype, "ellipsoid", void 0);
  37866. __decorate([
  37867. BABYLON.serialize()
  37868. ], FreeCamera.prototype, "checkCollisions", void 0);
  37869. __decorate([
  37870. BABYLON.serialize()
  37871. ], FreeCamera.prototype, "applyGravity", void 0);
  37872. return FreeCamera;
  37873. }(BABYLON.TargetCamera));
  37874. BABYLON.FreeCamera = FreeCamera;
  37875. })(BABYLON || (BABYLON = {}));
  37876. //# sourceMappingURL=babylon.freeCamera.js.map
  37877. var BABYLON;
  37878. (function (BABYLON) {
  37879. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37880. function ArcRotateCameraKeyboardMoveInput() {
  37881. this._keys = new Array();
  37882. this.keysUp = [38];
  37883. this.keysDown = [40];
  37884. this.keysLeft = [37];
  37885. this.keysRight = [39];
  37886. this.keysReset = [220];
  37887. this.panningSensibility = 50.0;
  37888. this.zoomingSensibility = 25.0;
  37889. this.useAltToZoom = true;
  37890. }
  37891. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37892. var _this = this;
  37893. if (this._onCanvasBlurObserver) {
  37894. return;
  37895. }
  37896. this._scene = this.camera.getScene();
  37897. this._engine = this._scene.getEngine();
  37898. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37899. _this._keys = [];
  37900. });
  37901. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37902. var evt = info.event;
  37903. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37904. _this._ctrlPressed = evt.ctrlKey;
  37905. _this._altPressed = evt.altKey;
  37906. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37907. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37908. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37909. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37910. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37911. var index = _this._keys.indexOf(evt.keyCode);
  37912. if (index === -1) {
  37913. _this._keys.push(evt.keyCode);
  37914. }
  37915. if (evt.preventDefault) {
  37916. if (!noPreventDefault) {
  37917. evt.preventDefault();
  37918. }
  37919. }
  37920. }
  37921. }
  37922. else {
  37923. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37924. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37925. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37926. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37927. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37928. var index = _this._keys.indexOf(evt.keyCode);
  37929. if (index >= 0) {
  37930. _this._keys.splice(index, 1);
  37931. }
  37932. if (evt.preventDefault) {
  37933. if (!noPreventDefault) {
  37934. evt.preventDefault();
  37935. }
  37936. }
  37937. }
  37938. }
  37939. });
  37940. };
  37941. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37942. if (this._scene) {
  37943. if (this._onKeyboardObserver) {
  37944. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37945. }
  37946. if (this._onCanvasBlurObserver) {
  37947. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37948. }
  37949. this._onKeyboardObserver = null;
  37950. this._onCanvasBlurObserver = null;
  37951. }
  37952. this._keys = [];
  37953. };
  37954. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37955. if (this._onKeyboardObserver) {
  37956. var camera = this.camera;
  37957. for (var index = 0; index < this._keys.length; index++) {
  37958. var keyCode = this._keys[index];
  37959. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37960. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37961. camera.inertialPanningX -= 1 / this.panningSensibility;
  37962. }
  37963. else {
  37964. camera.inertialAlphaOffset -= 0.01;
  37965. }
  37966. }
  37967. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37968. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37969. camera.inertialPanningY += 1 / this.panningSensibility;
  37970. }
  37971. else if (this._altPressed && this.useAltToZoom) {
  37972. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37973. }
  37974. else {
  37975. camera.inertialBetaOffset -= 0.01;
  37976. }
  37977. }
  37978. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37979. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37980. camera.inertialPanningX += 1 / this.panningSensibility;
  37981. }
  37982. else {
  37983. camera.inertialAlphaOffset += 0.01;
  37984. }
  37985. }
  37986. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37987. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37988. camera.inertialPanningY -= 1 / this.panningSensibility;
  37989. }
  37990. else if (this._altPressed && this.useAltToZoom) {
  37991. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37992. }
  37993. else {
  37994. camera.inertialBetaOffset += 0.01;
  37995. }
  37996. }
  37997. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37998. camera.restoreState();
  37999. }
  38000. }
  38001. }
  38002. };
  38003. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38004. return "ArcRotateCameraKeyboardMoveInput";
  38005. };
  38006. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38007. return "keyboard";
  38008. };
  38009. __decorate([
  38010. BABYLON.serialize()
  38011. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38012. __decorate([
  38013. BABYLON.serialize()
  38014. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38015. __decorate([
  38016. BABYLON.serialize()
  38017. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38018. __decorate([
  38019. BABYLON.serialize()
  38020. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38021. __decorate([
  38022. BABYLON.serialize()
  38023. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38024. __decorate([
  38025. BABYLON.serialize()
  38026. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38027. __decorate([
  38028. BABYLON.serialize()
  38029. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38030. __decorate([
  38031. BABYLON.serialize()
  38032. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38033. return ArcRotateCameraKeyboardMoveInput;
  38034. }());
  38035. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38036. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38037. })(BABYLON || (BABYLON = {}));
  38038. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38039. var BABYLON;
  38040. (function (BABYLON) {
  38041. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38042. function ArcRotateCameraMouseWheelInput() {
  38043. this.wheelPrecision = 3.0;
  38044. /**
  38045. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38046. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38047. */
  38048. this.wheelDeltaPercentage = 0;
  38049. }
  38050. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38051. var _this = this;
  38052. this._wheel = function (p, s) {
  38053. //sanity check - this should be a PointerWheel event.
  38054. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38055. return;
  38056. var event = p.event;
  38057. var delta = 0;
  38058. if (event.wheelDelta) {
  38059. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38060. }
  38061. else if (event.detail) {
  38062. delta = -event.detail / _this.wheelPrecision;
  38063. }
  38064. if (delta)
  38065. _this.camera.inertialRadiusOffset += delta;
  38066. if (event.preventDefault) {
  38067. if (!noPreventDefault) {
  38068. event.preventDefault();
  38069. }
  38070. }
  38071. };
  38072. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38073. };
  38074. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38075. if (this._observer && element) {
  38076. this.camera.getScene().onPointerObservable.remove(this._observer);
  38077. this._observer = null;
  38078. this._wheel = null;
  38079. }
  38080. };
  38081. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38082. return "ArcRotateCameraMouseWheelInput";
  38083. };
  38084. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38085. return "mousewheel";
  38086. };
  38087. __decorate([
  38088. BABYLON.serialize()
  38089. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38090. __decorate([
  38091. BABYLON.serialize()
  38092. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38093. return ArcRotateCameraMouseWheelInput;
  38094. }());
  38095. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38096. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38097. })(BABYLON || (BABYLON = {}));
  38098. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38099. var BABYLON;
  38100. (function (BABYLON) {
  38101. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38102. function ArcRotateCameraPointersInput() {
  38103. this.buttons = [0, 1, 2];
  38104. this.angularSensibilityX = 1000.0;
  38105. this.angularSensibilityY = 1000.0;
  38106. this.pinchPrecision = 12.0;
  38107. /**
  38108. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38109. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38110. */
  38111. this.pinchDeltaPercentage = 0;
  38112. this.panningSensibility = 1000.0;
  38113. this.multiTouchPanning = true;
  38114. this.multiTouchPanAndZoom = true;
  38115. this._isPanClick = false;
  38116. this.pinchInwards = true;
  38117. }
  38118. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38119. var _this = this;
  38120. var engine = this.camera.getEngine();
  38121. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38122. var pointA = null;
  38123. var pointB = null;
  38124. var previousPinchSquaredDistance = 0;
  38125. var initialDistance = 0;
  38126. var twoFingerActivityCount = 0;
  38127. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38128. this._pointerInput = function (p, s) {
  38129. var evt = p.event;
  38130. var isTouch = p.event.pointerType === "touch";
  38131. if (engine.isInVRExclusivePointerMode) {
  38132. return;
  38133. }
  38134. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38135. return;
  38136. }
  38137. var srcElement = (evt.srcElement || evt.target);
  38138. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38139. try {
  38140. srcElement.setPointerCapture(evt.pointerId);
  38141. }
  38142. catch (e) {
  38143. //Nothing to do with the error. Execution will continue.
  38144. }
  38145. // Manage panning with pan button click
  38146. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38147. // manage pointers
  38148. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38149. if (pointA === null) {
  38150. pointA = cacheSoloPointer;
  38151. }
  38152. else if (pointB === null) {
  38153. pointB = cacheSoloPointer;
  38154. }
  38155. if (!noPreventDefault) {
  38156. evt.preventDefault();
  38157. element.focus();
  38158. }
  38159. }
  38160. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38161. _this.camera.restoreState();
  38162. }
  38163. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38164. try {
  38165. srcElement.releasePointerCapture(evt.pointerId);
  38166. }
  38167. catch (e) {
  38168. //Nothing to do with the error.
  38169. }
  38170. cacheSoloPointer = null;
  38171. previousPinchSquaredDistance = 0;
  38172. previousMultiTouchPanPosition.isPaning = false;
  38173. previousMultiTouchPanPosition.isPinching = false;
  38174. twoFingerActivityCount = 0;
  38175. initialDistance = 0;
  38176. if (!isTouch) {
  38177. pointB = null; // Mouse and pen are mono pointer
  38178. }
  38179. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38180. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38181. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38182. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38183. if (engine.badOS) {
  38184. pointA = pointB = null;
  38185. }
  38186. else {
  38187. //only remove the impacted pointer in case of multitouch allowing on most
  38188. //platforms switching from rotate to zoom and pan seamlessly.
  38189. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38190. pointA = pointB;
  38191. pointB = null;
  38192. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38193. }
  38194. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38195. pointB = null;
  38196. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38197. }
  38198. else {
  38199. pointA = pointB = null;
  38200. }
  38201. }
  38202. if (!noPreventDefault) {
  38203. evt.preventDefault();
  38204. }
  38205. }
  38206. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38207. if (!noPreventDefault) {
  38208. evt.preventDefault();
  38209. }
  38210. // One button down
  38211. if (pointA && pointB === null && cacheSoloPointer) {
  38212. if (_this.panningSensibility !== 0 &&
  38213. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38214. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38215. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38216. }
  38217. else {
  38218. var offsetX = evt.clientX - cacheSoloPointer.x;
  38219. var offsetY = evt.clientY - cacheSoloPointer.y;
  38220. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38221. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38222. }
  38223. cacheSoloPointer.x = evt.clientX;
  38224. cacheSoloPointer.y = evt.clientY;
  38225. }
  38226. else if (pointA && pointB) {
  38227. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38228. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38229. ed.x = evt.clientX;
  38230. ed.y = evt.clientY;
  38231. var direction = _this.pinchInwards ? 1 : -1;
  38232. var distX = pointA.x - pointB.x;
  38233. var distY = pointA.y - pointB.y;
  38234. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38235. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38236. if (previousPinchSquaredDistance === 0) {
  38237. initialDistance = pinchDistance;
  38238. previousPinchSquaredDistance = pinchSquaredDistance;
  38239. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38240. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38241. return;
  38242. }
  38243. if (_this.multiTouchPanAndZoom) {
  38244. if (_this.pinchDeltaPercentage) {
  38245. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38246. }
  38247. else {
  38248. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38249. (_this.pinchPrecision *
  38250. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38251. direction);
  38252. }
  38253. if (_this.panningSensibility !== 0) {
  38254. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38255. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38256. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38257. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38258. previousMultiTouchPanPosition.x = pointersCenterX;
  38259. previousMultiTouchPanPosition.y = pointersCenterY;
  38260. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38261. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38262. }
  38263. }
  38264. else {
  38265. twoFingerActivityCount++;
  38266. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38267. if (_this.pinchDeltaPercentage) {
  38268. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38269. }
  38270. else {
  38271. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38272. (_this.pinchPrecision *
  38273. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38274. direction);
  38275. }
  38276. previousMultiTouchPanPosition.isPaning = false;
  38277. previousMultiTouchPanPosition.isPinching = true;
  38278. }
  38279. else {
  38280. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38281. if (!previousMultiTouchPanPosition.isPaning) {
  38282. previousMultiTouchPanPosition.isPaning = true;
  38283. previousMultiTouchPanPosition.isPinching = false;
  38284. previousMultiTouchPanPosition.x = ed.x;
  38285. previousMultiTouchPanPosition.y = ed.y;
  38286. return;
  38287. }
  38288. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38289. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38290. }
  38291. }
  38292. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38293. previousMultiTouchPanPosition.x = ed.x;
  38294. previousMultiTouchPanPosition.y = ed.y;
  38295. }
  38296. }
  38297. previousPinchSquaredDistance = pinchSquaredDistance;
  38298. }
  38299. }
  38300. };
  38301. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38302. this._onContextMenu = function (evt) {
  38303. evt.preventDefault();
  38304. };
  38305. if (!this.camera._useCtrlForPanning) {
  38306. element.addEventListener("contextmenu", this._onContextMenu, false);
  38307. }
  38308. this._onLostFocus = function () {
  38309. //this._keys = [];
  38310. pointA = pointB = null;
  38311. previousPinchSquaredDistance = 0;
  38312. previousMultiTouchPanPosition.isPaning = false;
  38313. previousMultiTouchPanPosition.isPinching = false;
  38314. twoFingerActivityCount = 0;
  38315. cacheSoloPointer = null;
  38316. initialDistance = 0;
  38317. };
  38318. this._onMouseMove = function (evt) {
  38319. if (!engine.isPointerLock) {
  38320. return;
  38321. }
  38322. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38323. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38324. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38325. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38326. if (!noPreventDefault) {
  38327. evt.preventDefault();
  38328. }
  38329. };
  38330. this._onGestureStart = function (e) {
  38331. if (window.MSGesture === undefined) {
  38332. return;
  38333. }
  38334. if (!_this._MSGestureHandler) {
  38335. _this._MSGestureHandler = new MSGesture();
  38336. _this._MSGestureHandler.target = element;
  38337. }
  38338. _this._MSGestureHandler.addPointer(e.pointerId);
  38339. };
  38340. this._onGesture = function (e) {
  38341. _this.camera.radius *= e.scale;
  38342. if (e.preventDefault) {
  38343. if (!noPreventDefault) {
  38344. e.stopPropagation();
  38345. e.preventDefault();
  38346. }
  38347. }
  38348. };
  38349. element.addEventListener("mousemove", this._onMouseMove, false);
  38350. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38351. element.addEventListener("MSGestureChange", this._onGesture, false);
  38352. BABYLON.Tools.RegisterTopRootEvents([
  38353. { name: "blur", handler: this._onLostFocus }
  38354. ]);
  38355. };
  38356. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38357. if (this._onLostFocus) {
  38358. BABYLON.Tools.UnregisterTopRootEvents([
  38359. { name: "blur", handler: this._onLostFocus }
  38360. ]);
  38361. }
  38362. if (element && this._observer) {
  38363. this.camera.getScene().onPointerObservable.remove(this._observer);
  38364. this._observer = null;
  38365. if (this._onContextMenu) {
  38366. element.removeEventListener("contextmenu", this._onContextMenu);
  38367. }
  38368. if (this._onMouseMove) {
  38369. element.removeEventListener("mousemove", this._onMouseMove);
  38370. }
  38371. if (this._onGestureStart) {
  38372. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38373. }
  38374. if (this._onGesture) {
  38375. element.removeEventListener("MSGestureChange", this._onGesture);
  38376. }
  38377. this._isPanClick = false;
  38378. this.pinchInwards = true;
  38379. this._onMouseMove = null;
  38380. this._onGestureStart = null;
  38381. this._onGesture = null;
  38382. this._MSGestureHandler = null;
  38383. this._onLostFocus = null;
  38384. this._onContextMenu = null;
  38385. }
  38386. };
  38387. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38388. return "ArcRotateCameraPointersInput";
  38389. };
  38390. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38391. return "pointers";
  38392. };
  38393. __decorate([
  38394. BABYLON.serialize()
  38395. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38396. __decorate([
  38397. BABYLON.serialize()
  38398. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38399. __decorate([
  38400. BABYLON.serialize()
  38401. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38402. __decorate([
  38403. BABYLON.serialize()
  38404. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38405. __decorate([
  38406. BABYLON.serialize()
  38407. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38408. __decorate([
  38409. BABYLON.serialize()
  38410. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38411. __decorate([
  38412. BABYLON.serialize()
  38413. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38414. __decorate([
  38415. BABYLON.serialize()
  38416. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38417. return ArcRotateCameraPointersInput;
  38418. }());
  38419. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38420. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38421. })(BABYLON || (BABYLON = {}));
  38422. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38423. var BABYLON;
  38424. (function (BABYLON) {
  38425. var ArcRotateCamera = /** @class */ (function (_super) {
  38426. __extends(ArcRotateCamera, _super);
  38427. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38428. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38429. _this.inertialAlphaOffset = 0;
  38430. _this.inertialBetaOffset = 0;
  38431. _this.inertialRadiusOffset = 0;
  38432. _this.lowerAlphaLimit = null;
  38433. _this.upperAlphaLimit = null;
  38434. _this.lowerBetaLimit = 0.01;
  38435. _this.upperBetaLimit = Math.PI;
  38436. _this.lowerRadiusLimit = null;
  38437. _this.upperRadiusLimit = null;
  38438. _this.inertialPanningX = 0;
  38439. _this.inertialPanningY = 0;
  38440. _this.pinchToPanMaxDistance = 20;
  38441. _this.panningDistanceLimit = null;
  38442. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38443. _this.panningInertia = 0.9;
  38444. //-- end properties for backward compatibility for inputs
  38445. _this.zoomOnFactor = 1;
  38446. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38447. _this.allowUpsideDown = true;
  38448. _this._viewMatrix = new BABYLON.Matrix();
  38449. // Panning
  38450. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38451. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38452. _this.checkCollisions = false;
  38453. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38454. _this._previousPosition = BABYLON.Vector3.Zero();
  38455. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38456. _this._newPosition = BABYLON.Vector3.Zero();
  38457. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38458. if (collidedMesh === void 0) { collidedMesh = null; }
  38459. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38460. newPosition.multiplyInPlace(_this._collider.radius);
  38461. }
  38462. if (!collidedMesh) {
  38463. _this._previousPosition.copyFrom(_this.position);
  38464. }
  38465. else {
  38466. _this.setPosition(newPosition);
  38467. if (_this.onCollide) {
  38468. _this.onCollide(collidedMesh);
  38469. }
  38470. }
  38471. // Recompute because of constraints
  38472. var cosa = Math.cos(_this.alpha);
  38473. var sina = Math.sin(_this.alpha);
  38474. var cosb = Math.cos(_this.beta);
  38475. var sinb = Math.sin(_this.beta);
  38476. if (sinb === 0) {
  38477. sinb = 0.0001;
  38478. }
  38479. var target = _this._getTargetPosition();
  38480. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38481. _this.position.copyFrom(_this._newPosition);
  38482. var up = _this.upVector;
  38483. if (_this.allowUpsideDown && _this.beta < 0) {
  38484. up = up.clone();
  38485. up = up.negate();
  38486. }
  38487. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38488. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38489. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38490. _this._collisionTriggered = false;
  38491. };
  38492. _this._target = BABYLON.Vector3.Zero();
  38493. if (target) {
  38494. _this.setTarget(target);
  38495. }
  38496. _this.alpha = alpha;
  38497. _this.beta = beta;
  38498. _this.radius = radius;
  38499. _this.getViewMatrix();
  38500. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38501. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38502. return _this;
  38503. }
  38504. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38505. get: function () {
  38506. return this._target;
  38507. },
  38508. set: function (value) {
  38509. this.setTarget(value);
  38510. },
  38511. enumerable: true,
  38512. configurable: true
  38513. });
  38514. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38515. //-- begin properties for backward compatibility for inputs
  38516. get: function () {
  38517. var pointers = this.inputs.attached["pointers"];
  38518. if (pointers)
  38519. return pointers.angularSensibilityX;
  38520. return 0;
  38521. },
  38522. set: function (value) {
  38523. var pointers = this.inputs.attached["pointers"];
  38524. if (pointers) {
  38525. pointers.angularSensibilityX = value;
  38526. }
  38527. },
  38528. enumerable: true,
  38529. configurable: true
  38530. });
  38531. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38532. get: function () {
  38533. var pointers = this.inputs.attached["pointers"];
  38534. if (pointers)
  38535. return pointers.angularSensibilityY;
  38536. return 0;
  38537. },
  38538. set: function (value) {
  38539. var pointers = this.inputs.attached["pointers"];
  38540. if (pointers) {
  38541. pointers.angularSensibilityY = value;
  38542. }
  38543. },
  38544. enumerable: true,
  38545. configurable: true
  38546. });
  38547. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38548. get: function () {
  38549. var pointers = this.inputs.attached["pointers"];
  38550. if (pointers)
  38551. return pointers.pinchPrecision;
  38552. return 0;
  38553. },
  38554. set: function (value) {
  38555. var pointers = this.inputs.attached["pointers"];
  38556. if (pointers) {
  38557. pointers.pinchPrecision = value;
  38558. }
  38559. },
  38560. enumerable: true,
  38561. configurable: true
  38562. });
  38563. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38564. get: function () {
  38565. var pointers = this.inputs.attached["pointers"];
  38566. if (pointers)
  38567. return pointers.pinchDeltaPercentage;
  38568. return 0;
  38569. },
  38570. set: function (value) {
  38571. var pointers = this.inputs.attached["pointers"];
  38572. if (pointers) {
  38573. pointers.pinchDeltaPercentage = value;
  38574. }
  38575. },
  38576. enumerable: true,
  38577. configurable: true
  38578. });
  38579. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38580. get: function () {
  38581. var pointers = this.inputs.attached["pointers"];
  38582. if (pointers)
  38583. return pointers.panningSensibility;
  38584. return 0;
  38585. },
  38586. set: function (value) {
  38587. var pointers = this.inputs.attached["pointers"];
  38588. if (pointers) {
  38589. pointers.panningSensibility = value;
  38590. }
  38591. },
  38592. enumerable: true,
  38593. configurable: true
  38594. });
  38595. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38596. get: function () {
  38597. var keyboard = this.inputs.attached["keyboard"];
  38598. if (keyboard)
  38599. return keyboard.keysUp;
  38600. return [];
  38601. },
  38602. set: function (value) {
  38603. var keyboard = this.inputs.attached["keyboard"];
  38604. if (keyboard)
  38605. keyboard.keysUp = value;
  38606. },
  38607. enumerable: true,
  38608. configurable: true
  38609. });
  38610. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38611. get: function () {
  38612. var keyboard = this.inputs.attached["keyboard"];
  38613. if (keyboard)
  38614. return keyboard.keysDown;
  38615. return [];
  38616. },
  38617. set: function (value) {
  38618. var keyboard = this.inputs.attached["keyboard"];
  38619. if (keyboard)
  38620. keyboard.keysDown = value;
  38621. },
  38622. enumerable: true,
  38623. configurable: true
  38624. });
  38625. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38626. get: function () {
  38627. var keyboard = this.inputs.attached["keyboard"];
  38628. if (keyboard)
  38629. return keyboard.keysLeft;
  38630. return [];
  38631. },
  38632. set: function (value) {
  38633. var keyboard = this.inputs.attached["keyboard"];
  38634. if (keyboard)
  38635. keyboard.keysLeft = value;
  38636. },
  38637. enumerable: true,
  38638. configurable: true
  38639. });
  38640. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38641. get: function () {
  38642. var keyboard = this.inputs.attached["keyboard"];
  38643. if (keyboard)
  38644. return keyboard.keysRight;
  38645. return [];
  38646. },
  38647. set: function (value) {
  38648. var keyboard = this.inputs.attached["keyboard"];
  38649. if (keyboard)
  38650. keyboard.keysRight = value;
  38651. },
  38652. enumerable: true,
  38653. configurable: true
  38654. });
  38655. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38656. get: function () {
  38657. var mousewheel = this.inputs.attached["mousewheel"];
  38658. if (mousewheel)
  38659. return mousewheel.wheelPrecision;
  38660. return 0;
  38661. },
  38662. set: function (value) {
  38663. var mousewheel = this.inputs.attached["mousewheel"];
  38664. if (mousewheel)
  38665. mousewheel.wheelPrecision = value;
  38666. },
  38667. enumerable: true,
  38668. configurable: true
  38669. });
  38670. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38671. get: function () {
  38672. var mousewheel = this.inputs.attached["mousewheel"];
  38673. if (mousewheel)
  38674. return mousewheel.wheelDeltaPercentage;
  38675. return 0;
  38676. },
  38677. set: function (value) {
  38678. var mousewheel = this.inputs.attached["mousewheel"];
  38679. if (mousewheel)
  38680. mousewheel.wheelDeltaPercentage = value;
  38681. },
  38682. enumerable: true,
  38683. configurable: true
  38684. });
  38685. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38686. get: function () {
  38687. return this._bouncingBehavior;
  38688. },
  38689. enumerable: true,
  38690. configurable: true
  38691. });
  38692. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38693. get: function () {
  38694. return this._bouncingBehavior != null;
  38695. },
  38696. set: function (value) {
  38697. if (value === this.useBouncingBehavior) {
  38698. return;
  38699. }
  38700. if (value) {
  38701. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38702. this.addBehavior(this._bouncingBehavior);
  38703. }
  38704. else if (this._bouncingBehavior) {
  38705. this.removeBehavior(this._bouncingBehavior);
  38706. this._bouncingBehavior = null;
  38707. }
  38708. },
  38709. enumerable: true,
  38710. configurable: true
  38711. });
  38712. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38713. get: function () {
  38714. return this._framingBehavior;
  38715. },
  38716. enumerable: true,
  38717. configurable: true
  38718. });
  38719. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38720. get: function () {
  38721. return this._framingBehavior != null;
  38722. },
  38723. set: function (value) {
  38724. if (value === this.useFramingBehavior) {
  38725. return;
  38726. }
  38727. if (value) {
  38728. this._framingBehavior = new BABYLON.FramingBehavior();
  38729. this.addBehavior(this._framingBehavior);
  38730. }
  38731. else if (this._framingBehavior) {
  38732. this.removeBehavior(this._framingBehavior);
  38733. this._framingBehavior = null;
  38734. }
  38735. },
  38736. enumerable: true,
  38737. configurable: true
  38738. });
  38739. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38740. get: function () {
  38741. return this._autoRotationBehavior;
  38742. },
  38743. enumerable: true,
  38744. configurable: true
  38745. });
  38746. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38747. get: function () {
  38748. return this._autoRotationBehavior != null;
  38749. },
  38750. set: function (value) {
  38751. if (value === this.useAutoRotationBehavior) {
  38752. return;
  38753. }
  38754. if (value) {
  38755. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38756. this.addBehavior(this._autoRotationBehavior);
  38757. }
  38758. else if (this._autoRotationBehavior) {
  38759. this.removeBehavior(this._autoRotationBehavior);
  38760. this._autoRotationBehavior = null;
  38761. }
  38762. },
  38763. enumerable: true,
  38764. configurable: true
  38765. });
  38766. // Cache
  38767. ArcRotateCamera.prototype._initCache = function () {
  38768. _super.prototype._initCache.call(this);
  38769. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38770. this._cache.alpha = undefined;
  38771. this._cache.beta = undefined;
  38772. this._cache.radius = undefined;
  38773. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38774. };
  38775. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38776. if (!ignoreParentClass) {
  38777. _super.prototype._updateCache.call(this);
  38778. }
  38779. this._cache._target.copyFrom(this._getTargetPosition());
  38780. this._cache.alpha = this.alpha;
  38781. this._cache.beta = this.beta;
  38782. this._cache.radius = this.radius;
  38783. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38784. };
  38785. ArcRotateCamera.prototype._getTargetPosition = function () {
  38786. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38787. var pos = this._targetHost.getAbsolutePosition();
  38788. if (this._targetBoundingCenter) {
  38789. pos.addToRef(this._targetBoundingCenter, this._target);
  38790. }
  38791. else {
  38792. this._target.copyFrom(pos);
  38793. }
  38794. }
  38795. var lockedTargetPosition = this._getLockedTargetPosition();
  38796. if (lockedTargetPosition) {
  38797. return lockedTargetPosition;
  38798. }
  38799. return this._target;
  38800. };
  38801. ArcRotateCamera.prototype.storeState = function () {
  38802. this._storedAlpha = this.alpha;
  38803. this._storedBeta = this.beta;
  38804. this._storedRadius = this.radius;
  38805. this._storedTarget = this._getTargetPosition().clone();
  38806. return _super.prototype.storeState.call(this);
  38807. };
  38808. /**
  38809. * Restored camera state. You must call storeState() first
  38810. */
  38811. ArcRotateCamera.prototype._restoreStateValues = function () {
  38812. if (!_super.prototype._restoreStateValues.call(this)) {
  38813. return false;
  38814. }
  38815. this.alpha = this._storedAlpha;
  38816. this.beta = this._storedBeta;
  38817. this.radius = this._storedRadius;
  38818. this.setTarget(this._storedTarget.clone());
  38819. this.inertialAlphaOffset = 0;
  38820. this.inertialBetaOffset = 0;
  38821. this.inertialRadiusOffset = 0;
  38822. this.inertialPanningX = 0;
  38823. this.inertialPanningY = 0;
  38824. return true;
  38825. };
  38826. // Synchronized
  38827. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38828. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38829. return false;
  38830. return this._cache._target.equals(this._getTargetPosition())
  38831. && this._cache.alpha === this.alpha
  38832. && this._cache.beta === this.beta
  38833. && this._cache.radius === this.radius
  38834. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38835. };
  38836. // Methods
  38837. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38838. var _this = this;
  38839. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38840. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38841. this._useCtrlForPanning = useCtrlForPanning;
  38842. this._panningMouseButton = panningMouseButton;
  38843. this.inputs.attachElement(element, noPreventDefault);
  38844. this._reset = function () {
  38845. _this.inertialAlphaOffset = 0;
  38846. _this.inertialBetaOffset = 0;
  38847. _this.inertialRadiusOffset = 0;
  38848. _this.inertialPanningX = 0;
  38849. _this.inertialPanningY = 0;
  38850. };
  38851. };
  38852. ArcRotateCamera.prototype.detachControl = function (element) {
  38853. this.inputs.detachElement(element);
  38854. if (this._reset) {
  38855. this._reset();
  38856. }
  38857. };
  38858. ArcRotateCamera.prototype._checkInputs = function () {
  38859. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38860. if (this._collisionTriggered) {
  38861. return;
  38862. }
  38863. this.inputs.checkInputs();
  38864. // Inertia
  38865. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38866. if (this.getScene().useRightHandedSystem) {
  38867. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38868. }
  38869. else {
  38870. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38871. }
  38872. this.beta += this.inertialBetaOffset;
  38873. this.radius -= this.inertialRadiusOffset;
  38874. this.inertialAlphaOffset *= this.inertia;
  38875. this.inertialBetaOffset *= this.inertia;
  38876. this.inertialRadiusOffset *= this.inertia;
  38877. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38878. this.inertialAlphaOffset = 0;
  38879. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38880. this.inertialBetaOffset = 0;
  38881. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38882. this.inertialRadiusOffset = 0;
  38883. }
  38884. // Panning inertia
  38885. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38886. if (!this._localDirection) {
  38887. this._localDirection = BABYLON.Vector3.Zero();
  38888. this._transformedDirection = BABYLON.Vector3.Zero();
  38889. }
  38890. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38891. this._localDirection.multiplyInPlace(this.panningAxis);
  38892. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38893. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38894. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38895. if (!this.panningAxis.y) {
  38896. this._transformedDirection.y = 0;
  38897. }
  38898. if (!this._targetHost) {
  38899. if (this.panningDistanceLimit) {
  38900. this._transformedDirection.addInPlace(this._target);
  38901. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38902. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38903. this._target.copyFrom(this._transformedDirection);
  38904. }
  38905. }
  38906. else {
  38907. this._target.addInPlace(this._transformedDirection);
  38908. }
  38909. }
  38910. this.inertialPanningX *= this.panningInertia;
  38911. this.inertialPanningY *= this.panningInertia;
  38912. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38913. this.inertialPanningX = 0;
  38914. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38915. this.inertialPanningY = 0;
  38916. }
  38917. // Limits
  38918. this._checkLimits();
  38919. _super.prototype._checkInputs.call(this);
  38920. };
  38921. ArcRotateCamera.prototype._checkLimits = function () {
  38922. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38923. if (this.allowUpsideDown && this.beta > Math.PI) {
  38924. this.beta = this.beta - (2 * Math.PI);
  38925. }
  38926. }
  38927. else {
  38928. if (this.beta < this.lowerBetaLimit) {
  38929. this.beta = this.lowerBetaLimit;
  38930. }
  38931. }
  38932. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38933. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38934. this.beta = this.beta + (2 * Math.PI);
  38935. }
  38936. }
  38937. else {
  38938. if (this.beta > this.upperBetaLimit) {
  38939. this.beta = this.upperBetaLimit;
  38940. }
  38941. }
  38942. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38943. this.alpha = this.lowerAlphaLimit;
  38944. }
  38945. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38946. this.alpha = this.upperAlphaLimit;
  38947. }
  38948. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38949. this.radius = this.lowerRadiusLimit;
  38950. }
  38951. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38952. this.radius = this.upperRadiusLimit;
  38953. }
  38954. };
  38955. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38956. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38957. this.radius = radiusv3.length();
  38958. if (this.radius === 0) {
  38959. this.radius = 0.0001; // Just to avoid division by zero
  38960. }
  38961. // Alpha
  38962. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38963. if (radiusv3.z < 0) {
  38964. this.alpha = 2 * Math.PI - this.alpha;
  38965. }
  38966. // Beta
  38967. this.beta = Math.acos(radiusv3.y / this.radius);
  38968. this._checkLimits();
  38969. };
  38970. ArcRotateCamera.prototype.setPosition = function (position) {
  38971. if (this.position.equals(position)) {
  38972. return;
  38973. }
  38974. this.position.copyFrom(position);
  38975. this.rebuildAnglesAndRadius();
  38976. };
  38977. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38978. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38979. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38980. if (target.getBoundingInfo) {
  38981. if (toBoundingCenter) {
  38982. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38983. }
  38984. else {
  38985. this._targetBoundingCenter = null;
  38986. }
  38987. this._targetHost = target;
  38988. this._target = this._getTargetPosition();
  38989. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38990. }
  38991. else {
  38992. var newTarget = target;
  38993. var currentTarget = this._getTargetPosition();
  38994. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38995. return;
  38996. }
  38997. this._targetHost = null;
  38998. this._target = newTarget;
  38999. this._targetBoundingCenter = null;
  39000. this.onMeshTargetChangedObservable.notifyObservers(null);
  39001. }
  39002. this.rebuildAnglesAndRadius();
  39003. };
  39004. ArcRotateCamera.prototype._getViewMatrix = function () {
  39005. // Compute
  39006. var cosa = Math.cos(this.alpha);
  39007. var sina = Math.sin(this.alpha);
  39008. var cosb = Math.cos(this.beta);
  39009. var sinb = Math.sin(this.beta);
  39010. if (sinb === 0) {
  39011. sinb = 0.0001;
  39012. }
  39013. var target = this._getTargetPosition();
  39014. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39015. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39016. if (!this._collider) {
  39017. this._collider = new BABYLON.Collider();
  39018. }
  39019. this._collider.radius = this.collisionRadius;
  39020. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39021. this._collisionTriggered = true;
  39022. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39023. }
  39024. else {
  39025. this.position.copyFrom(this._newPosition);
  39026. var up = this.upVector;
  39027. if (this.allowUpsideDown && sinb < 0) {
  39028. up = up.clone();
  39029. up = up.negate();
  39030. }
  39031. if (this.getScene().useRightHandedSystem) {
  39032. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39033. }
  39034. else {
  39035. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39036. }
  39037. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39038. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39039. }
  39040. this._currentTarget = target;
  39041. return this._viewMatrix;
  39042. };
  39043. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39044. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39045. meshes = meshes || this.getScene().meshes;
  39046. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39047. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39048. this.radius = distance * this.zoomOnFactor;
  39049. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39050. };
  39051. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39052. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39053. var meshesOrMinMaxVector;
  39054. var distance;
  39055. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39056. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39057. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39058. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39059. }
  39060. else {
  39061. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39062. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39063. distance = minMaxVectorAndDistance.distance;
  39064. }
  39065. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39066. if (!doNotUpdateMaxZ) {
  39067. this.maxZ = distance * 2;
  39068. }
  39069. };
  39070. /**
  39071. * @override
  39072. * Override Camera.createRigCamera
  39073. */
  39074. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39075. var alphaShift = 0;
  39076. switch (this.cameraRigMode) {
  39077. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39078. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39079. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39080. case BABYLON.Camera.RIG_MODE_VR:
  39081. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39082. break;
  39083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39084. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39085. break;
  39086. }
  39087. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39088. rigCam._cameraRigParams = {};
  39089. return rigCam;
  39090. };
  39091. /**
  39092. * @override
  39093. * Override Camera._updateRigCameras
  39094. */
  39095. ArcRotateCamera.prototype._updateRigCameras = function () {
  39096. var camLeft = this._rigCameras[0];
  39097. var camRight = this._rigCameras[1];
  39098. camLeft.beta = camRight.beta = this.beta;
  39099. camLeft.radius = camRight.radius = this.radius;
  39100. switch (this.cameraRigMode) {
  39101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39102. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39103. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39104. case BABYLON.Camera.RIG_MODE_VR:
  39105. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39106. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39107. break;
  39108. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39109. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39110. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39111. break;
  39112. }
  39113. _super.prototype._updateRigCameras.call(this);
  39114. };
  39115. ArcRotateCamera.prototype.dispose = function () {
  39116. this.inputs.clear();
  39117. _super.prototype.dispose.call(this);
  39118. };
  39119. ArcRotateCamera.prototype.getClassName = function () {
  39120. return "ArcRotateCamera";
  39121. };
  39122. __decorate([
  39123. BABYLON.serialize()
  39124. ], ArcRotateCamera.prototype, "alpha", void 0);
  39125. __decorate([
  39126. BABYLON.serialize()
  39127. ], ArcRotateCamera.prototype, "beta", void 0);
  39128. __decorate([
  39129. BABYLON.serialize()
  39130. ], ArcRotateCamera.prototype, "radius", void 0);
  39131. __decorate([
  39132. BABYLON.serializeAsVector3("target")
  39133. ], ArcRotateCamera.prototype, "_target", void 0);
  39134. __decorate([
  39135. BABYLON.serialize()
  39136. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39137. __decorate([
  39138. BABYLON.serialize()
  39139. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39140. __decorate([
  39141. BABYLON.serialize()
  39142. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39143. __decorate([
  39144. BABYLON.serialize()
  39145. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39146. __decorate([
  39147. BABYLON.serialize()
  39148. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39149. __decorate([
  39150. BABYLON.serialize()
  39151. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39152. __decorate([
  39153. BABYLON.serialize()
  39154. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39155. __decorate([
  39156. BABYLON.serialize()
  39157. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39158. __decorate([
  39159. BABYLON.serialize()
  39160. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39161. __decorate([
  39162. BABYLON.serialize()
  39163. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39164. __decorate([
  39165. BABYLON.serialize()
  39166. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39167. __decorate([
  39168. BABYLON.serialize()
  39169. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39170. __decorate([
  39171. BABYLON.serialize()
  39172. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39173. __decorate([
  39174. BABYLON.serializeAsVector3()
  39175. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39176. __decorate([
  39177. BABYLON.serialize()
  39178. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39179. __decorate([
  39180. BABYLON.serialize()
  39181. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39182. __decorate([
  39183. BABYLON.serialize()
  39184. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39185. return ArcRotateCamera;
  39186. }(BABYLON.TargetCamera));
  39187. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39188. })(BABYLON || (BABYLON = {}));
  39189. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39190. var BABYLON;
  39191. (function (BABYLON) {
  39192. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39193. __extends(ArcRotateCameraInputsManager, _super);
  39194. function ArcRotateCameraInputsManager(camera) {
  39195. return _super.call(this, camera) || this;
  39196. }
  39197. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39198. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39199. return this;
  39200. };
  39201. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39202. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39203. return this;
  39204. };
  39205. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39206. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39207. return this;
  39208. };
  39209. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39210. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39211. return this;
  39212. };
  39213. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39214. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39215. return this;
  39216. };
  39217. return ArcRotateCameraInputsManager;
  39218. }(BABYLON.CameraInputsManager));
  39219. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39220. })(BABYLON || (BABYLON = {}));
  39221. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39222. var BABYLON;
  39223. (function (BABYLON) {
  39224. var HemisphericLight = /** @class */ (function (_super) {
  39225. __extends(HemisphericLight, _super);
  39226. /**
  39227. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39228. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39229. * The HemisphericLight can't cast shadows.
  39230. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39231. */
  39232. function HemisphericLight(name, direction, scene) {
  39233. var _this = _super.call(this, name, scene) || this;
  39234. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39235. _this.direction = direction || BABYLON.Vector3.Up();
  39236. return _this;
  39237. }
  39238. HemisphericLight.prototype._buildUniformLayout = function () {
  39239. this._uniformBuffer.addUniform("vLightData", 4);
  39240. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39241. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39242. this._uniformBuffer.addUniform("vLightGround", 3);
  39243. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39244. this._uniformBuffer.addUniform("depthValues", 2);
  39245. this._uniformBuffer.create();
  39246. };
  39247. /**
  39248. * Returns the string "HemisphericLight".
  39249. */
  39250. HemisphericLight.prototype.getClassName = function () {
  39251. return "HemisphericLight";
  39252. };
  39253. /**
  39254. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39255. * Returns the updated direction.
  39256. */
  39257. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39258. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39259. return this.direction;
  39260. };
  39261. HemisphericLight.prototype.getShadowGenerator = function () {
  39262. return null;
  39263. };
  39264. /**
  39265. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39266. * Returns the HemisphericLight.
  39267. */
  39268. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39269. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39270. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39271. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39272. return this;
  39273. };
  39274. HemisphericLight.prototype._getWorldMatrix = function () {
  39275. if (!this._worldMatrix) {
  39276. this._worldMatrix = BABYLON.Matrix.Identity();
  39277. }
  39278. return this._worldMatrix;
  39279. };
  39280. /**
  39281. * Returns the integer 3.
  39282. */
  39283. HemisphericLight.prototype.getTypeID = function () {
  39284. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39285. };
  39286. __decorate([
  39287. BABYLON.serializeAsColor3()
  39288. ], HemisphericLight.prototype, "groundColor", void 0);
  39289. __decorate([
  39290. BABYLON.serializeAsVector3()
  39291. ], HemisphericLight.prototype, "direction", void 0);
  39292. return HemisphericLight;
  39293. }(BABYLON.Light));
  39294. BABYLON.HemisphericLight = HemisphericLight;
  39295. })(BABYLON || (BABYLON = {}));
  39296. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39297. var BABYLON;
  39298. (function (BABYLON) {
  39299. var ShadowLight = /** @class */ (function (_super) {
  39300. __extends(ShadowLight, _super);
  39301. function ShadowLight() {
  39302. var _this = _super !== null && _super.apply(this, arguments) || this;
  39303. _this._needProjectionMatrixCompute = true;
  39304. return _this;
  39305. }
  39306. Object.defineProperty(ShadowLight.prototype, "direction", {
  39307. get: function () {
  39308. return this._direction;
  39309. },
  39310. set: function (value) {
  39311. this._direction = value;
  39312. },
  39313. enumerable: true,
  39314. configurable: true
  39315. });
  39316. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39317. get: function () {
  39318. return this._shadowMinZ;
  39319. },
  39320. set: function (value) {
  39321. this._shadowMinZ = value;
  39322. this.forceProjectionMatrixCompute();
  39323. },
  39324. enumerable: true,
  39325. configurable: true
  39326. });
  39327. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39328. get: function () {
  39329. return this._shadowMaxZ;
  39330. },
  39331. set: function (value) {
  39332. this._shadowMaxZ = value;
  39333. this.forceProjectionMatrixCompute();
  39334. },
  39335. enumerable: true,
  39336. configurable: true
  39337. });
  39338. /**
  39339. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39340. */
  39341. ShadowLight.prototype.computeTransformedInformation = function () {
  39342. if (this.parent && this.parent.getWorldMatrix) {
  39343. if (!this.transformedPosition) {
  39344. this.transformedPosition = BABYLON.Vector3.Zero();
  39345. }
  39346. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39347. // In case the direction is present.
  39348. if (this.direction) {
  39349. if (!this.transformedDirection) {
  39350. this.transformedDirection = BABYLON.Vector3.Zero();
  39351. }
  39352. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39353. }
  39354. return true;
  39355. }
  39356. return false;
  39357. };
  39358. /**
  39359. * Return the depth scale used for the shadow map.
  39360. */
  39361. ShadowLight.prototype.getDepthScale = function () {
  39362. return 50.0;
  39363. };
  39364. /**
  39365. * Returns the light direction (Vector3) for any passed face index.
  39366. */
  39367. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39368. return this.transformedDirection ? this.transformedDirection : this.direction;
  39369. };
  39370. /**
  39371. * Returns the DirectionalLight absolute position in the World.
  39372. */
  39373. ShadowLight.prototype.getAbsolutePosition = function () {
  39374. return this.transformedPosition ? this.transformedPosition : this.position;
  39375. };
  39376. /**
  39377. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39378. * Returns the updated DirectionalLight direction (Vector3).
  39379. */
  39380. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39381. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39382. return this.direction;
  39383. };
  39384. /**
  39385. * Returns the light rotation (Vector3).
  39386. */
  39387. ShadowLight.prototype.getRotation = function () {
  39388. this.direction.normalize();
  39389. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39390. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39391. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39392. };
  39393. /**
  39394. * Boolean : false by default.
  39395. */
  39396. ShadowLight.prototype.needCube = function () {
  39397. return false;
  39398. };
  39399. /**
  39400. * Specifies wether or not the projection matrix should be recomputed this frame.
  39401. */
  39402. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39403. return this._needProjectionMatrixCompute;
  39404. };
  39405. /**
  39406. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39407. */
  39408. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39409. this._needProjectionMatrixCompute = true;
  39410. };
  39411. /**
  39412. * Get the world matrix of the sahdow lights.
  39413. */
  39414. ShadowLight.prototype._getWorldMatrix = function () {
  39415. if (!this._worldMatrix) {
  39416. this._worldMatrix = BABYLON.Matrix.Identity();
  39417. }
  39418. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39419. return this._worldMatrix;
  39420. };
  39421. /**
  39422. * Gets the minZ used for shadow according to both the scene and the light.
  39423. * @param activeCamera
  39424. */
  39425. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39426. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39427. };
  39428. /**
  39429. * Gets the maxZ used for shadow according to both the scene and the light.
  39430. * @param activeCamera
  39431. */
  39432. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39433. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39434. };
  39435. /**
  39436. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39437. * Returns the light.
  39438. */
  39439. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39440. if (this.customProjectionMatrixBuilder) {
  39441. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39442. }
  39443. else {
  39444. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39445. }
  39446. return this;
  39447. };
  39448. __decorate([
  39449. BABYLON.serializeAsVector3()
  39450. ], ShadowLight.prototype, "position", void 0);
  39451. __decorate([
  39452. BABYLON.serializeAsVector3()
  39453. ], ShadowLight.prototype, "direction", null);
  39454. __decorate([
  39455. BABYLON.serialize()
  39456. ], ShadowLight.prototype, "shadowMinZ", null);
  39457. __decorate([
  39458. BABYLON.serialize()
  39459. ], ShadowLight.prototype, "shadowMaxZ", null);
  39460. return ShadowLight;
  39461. }(BABYLON.Light));
  39462. BABYLON.ShadowLight = ShadowLight;
  39463. })(BABYLON || (BABYLON = {}));
  39464. //# sourceMappingURL=babylon.shadowLight.js.map
  39465. var BABYLON;
  39466. (function (BABYLON) {
  39467. var PointLight = /** @class */ (function (_super) {
  39468. __extends(PointLight, _super);
  39469. /**
  39470. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39471. * A PointLight emits the light in every direction.
  39472. * It can cast shadows.
  39473. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39474. * ```javascript
  39475. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39476. * ```
  39477. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39478. */
  39479. function PointLight(name, position, scene) {
  39480. var _this = _super.call(this, name, scene) || this;
  39481. _this._shadowAngle = Math.PI / 2;
  39482. _this.position = position;
  39483. return _this;
  39484. }
  39485. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39486. /**
  39487. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39488. * This specifies what angle the shadow will use to be created.
  39489. *
  39490. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39491. */
  39492. get: function () {
  39493. return this._shadowAngle;
  39494. },
  39495. /**
  39496. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39497. * This specifies what angle the shadow will use to be created.
  39498. *
  39499. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39500. */
  39501. set: function (value) {
  39502. this._shadowAngle = value;
  39503. this.forceProjectionMatrixCompute();
  39504. },
  39505. enumerable: true,
  39506. configurable: true
  39507. });
  39508. Object.defineProperty(PointLight.prototype, "direction", {
  39509. get: function () {
  39510. return this._direction;
  39511. },
  39512. /**
  39513. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39514. */
  39515. set: function (value) {
  39516. var previousNeedCube = this.needCube();
  39517. this._direction = value;
  39518. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39519. this._shadowGenerator.recreateShadowMap();
  39520. }
  39521. },
  39522. enumerable: true,
  39523. configurable: true
  39524. });
  39525. /**
  39526. * Returns the string "PointLight"
  39527. */
  39528. PointLight.prototype.getClassName = function () {
  39529. return "PointLight";
  39530. };
  39531. /**
  39532. * Returns the integer 0.
  39533. */
  39534. PointLight.prototype.getTypeID = function () {
  39535. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39536. };
  39537. /**
  39538. * Specifies wether or not the shadowmap should be a cube texture.
  39539. */
  39540. PointLight.prototype.needCube = function () {
  39541. return !this.direction;
  39542. };
  39543. /**
  39544. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39545. */
  39546. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39547. if (this.direction) {
  39548. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39549. }
  39550. else {
  39551. switch (faceIndex) {
  39552. case 0:
  39553. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39554. case 1:
  39555. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39556. case 2:
  39557. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39558. case 3:
  39559. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39560. case 4:
  39561. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39562. case 5:
  39563. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39564. }
  39565. }
  39566. return BABYLON.Vector3.Zero();
  39567. };
  39568. /**
  39569. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39570. * - fov = PI / 2
  39571. * - aspect ratio : 1.0
  39572. * - z-near and far equal to the active camera minZ and maxZ.
  39573. * Returns the PointLight.
  39574. */
  39575. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39576. var activeCamera = this.getScene().activeCamera;
  39577. if (!activeCamera) {
  39578. return;
  39579. }
  39580. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39581. };
  39582. PointLight.prototype._buildUniformLayout = function () {
  39583. this._uniformBuffer.addUniform("vLightData", 4);
  39584. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39585. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39586. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39587. this._uniformBuffer.addUniform("depthValues", 2);
  39588. this._uniformBuffer.create();
  39589. };
  39590. /**
  39591. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39592. * Returns the PointLight.
  39593. */
  39594. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39595. if (this.computeTransformedInformation()) {
  39596. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39597. return this;
  39598. }
  39599. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39600. return this;
  39601. };
  39602. __decorate([
  39603. BABYLON.serialize()
  39604. ], PointLight.prototype, "shadowAngle", null);
  39605. return PointLight;
  39606. }(BABYLON.ShadowLight));
  39607. BABYLON.PointLight = PointLight;
  39608. })(BABYLON || (BABYLON = {}));
  39609. //# sourceMappingURL=babylon.pointLight.js.map
  39610. var BABYLON;
  39611. (function (BABYLON) {
  39612. var DirectionalLight = /** @class */ (function (_super) {
  39613. __extends(DirectionalLight, _super);
  39614. /**
  39615. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39616. * The directional light is emitted from everywhere in the given direction.
  39617. * It can cast shawdows.
  39618. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39619. */
  39620. function DirectionalLight(name, direction, scene) {
  39621. var _this = _super.call(this, name, scene) || this;
  39622. _this._shadowFrustumSize = 0;
  39623. _this._shadowOrthoScale = 0.5;
  39624. _this.autoUpdateExtends = true;
  39625. // Cache
  39626. _this._orthoLeft = Number.MAX_VALUE;
  39627. _this._orthoRight = Number.MIN_VALUE;
  39628. _this._orthoTop = Number.MIN_VALUE;
  39629. _this._orthoBottom = Number.MAX_VALUE;
  39630. _this.position = direction.scale(-1.0);
  39631. _this.direction = direction;
  39632. return _this;
  39633. }
  39634. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39635. /**
  39636. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39637. */
  39638. get: function () {
  39639. return this._shadowFrustumSize;
  39640. },
  39641. /**
  39642. * Specifies a fix frustum size for the shadow generation.
  39643. */
  39644. set: function (value) {
  39645. this._shadowFrustumSize = value;
  39646. this.forceProjectionMatrixCompute();
  39647. },
  39648. enumerable: true,
  39649. configurable: true
  39650. });
  39651. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39652. get: function () {
  39653. return this._shadowOrthoScale;
  39654. },
  39655. set: function (value) {
  39656. this._shadowOrthoScale = value;
  39657. this.forceProjectionMatrixCompute();
  39658. },
  39659. enumerable: true,
  39660. configurable: true
  39661. });
  39662. /**
  39663. * Returns the string "DirectionalLight".
  39664. */
  39665. DirectionalLight.prototype.getClassName = function () {
  39666. return "DirectionalLight";
  39667. };
  39668. /**
  39669. * Returns the integer 1.
  39670. */
  39671. DirectionalLight.prototype.getTypeID = function () {
  39672. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39673. };
  39674. /**
  39675. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39676. * Returns the DirectionalLight Shadow projection matrix.
  39677. */
  39678. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39679. if (this.shadowFrustumSize > 0) {
  39680. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39681. }
  39682. else {
  39683. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39684. }
  39685. };
  39686. /**
  39687. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39688. * Returns the DirectionalLight Shadow projection matrix.
  39689. */
  39690. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39691. var activeCamera = this.getScene().activeCamera;
  39692. if (!activeCamera) {
  39693. return;
  39694. }
  39695. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39696. };
  39697. /**
  39698. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39699. * Returns the DirectionalLight Shadow projection matrix.
  39700. */
  39701. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39702. var activeCamera = this.getScene().activeCamera;
  39703. if (!activeCamera) {
  39704. return;
  39705. }
  39706. // Check extends
  39707. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39708. var tempVector3 = BABYLON.Vector3.Zero();
  39709. this._orthoLeft = Number.MAX_VALUE;
  39710. this._orthoRight = Number.MIN_VALUE;
  39711. this._orthoTop = Number.MIN_VALUE;
  39712. this._orthoBottom = Number.MAX_VALUE;
  39713. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39714. var mesh = renderList[meshIndex];
  39715. if (!mesh) {
  39716. continue;
  39717. }
  39718. var boundingInfo = mesh.getBoundingInfo();
  39719. if (!boundingInfo) {
  39720. continue;
  39721. }
  39722. var boundingBox = boundingInfo.boundingBox;
  39723. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39724. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39725. if (tempVector3.x < this._orthoLeft)
  39726. this._orthoLeft = tempVector3.x;
  39727. if (tempVector3.y < this._orthoBottom)
  39728. this._orthoBottom = tempVector3.y;
  39729. if (tempVector3.x > this._orthoRight)
  39730. this._orthoRight = tempVector3.x;
  39731. if (tempVector3.y > this._orthoTop)
  39732. this._orthoTop = tempVector3.y;
  39733. }
  39734. }
  39735. }
  39736. var xOffset = this._orthoRight - this._orthoLeft;
  39737. var yOffset = this._orthoTop - this._orthoBottom;
  39738. 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);
  39739. };
  39740. DirectionalLight.prototype._buildUniformLayout = function () {
  39741. this._uniformBuffer.addUniform("vLightData", 4);
  39742. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39743. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39744. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39745. this._uniformBuffer.addUniform("depthValues", 2);
  39746. this._uniformBuffer.create();
  39747. };
  39748. /**
  39749. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39750. * Returns the DirectionalLight.
  39751. */
  39752. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39753. if (this.computeTransformedInformation()) {
  39754. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39755. return this;
  39756. }
  39757. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39758. return this;
  39759. };
  39760. /**
  39761. * Gets the minZ used for shadow according to both the scene and the light.
  39762. *
  39763. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39764. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39765. * @param activeCamera
  39766. */
  39767. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39768. return 1;
  39769. };
  39770. /**
  39771. * Gets the maxZ used for shadow according to both the scene and the light.
  39772. *
  39773. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39774. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39775. * @param activeCamera
  39776. */
  39777. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39778. return 1;
  39779. };
  39780. __decorate([
  39781. BABYLON.serialize()
  39782. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39783. __decorate([
  39784. BABYLON.serialize()
  39785. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39786. __decorate([
  39787. BABYLON.serialize()
  39788. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39789. return DirectionalLight;
  39790. }(BABYLON.ShadowLight));
  39791. BABYLON.DirectionalLight = DirectionalLight;
  39792. })(BABYLON || (BABYLON = {}));
  39793. //# sourceMappingURL=babylon.directionalLight.js.map
  39794. var BABYLON;
  39795. (function (BABYLON) {
  39796. var SpotLight = /** @class */ (function (_super) {
  39797. __extends(SpotLight, _super);
  39798. /**
  39799. * Creates a SpotLight object in the scene with the passed parameters :
  39800. * - `position` (Vector3) is the initial SpotLight position,
  39801. * - `direction` (Vector3) is the initial SpotLight direction,
  39802. * - `angle` (float, in radians) is the spot light cone angle,
  39803. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39804. * A spot light is a simply light oriented cone.
  39805. * It can cast shadows.
  39806. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39807. */
  39808. function SpotLight(name, position, direction, angle, exponent, scene) {
  39809. var _this = _super.call(this, name, scene) || this;
  39810. _this.position = position;
  39811. _this.direction = direction;
  39812. _this.angle = angle;
  39813. _this.exponent = exponent;
  39814. return _this;
  39815. }
  39816. Object.defineProperty(SpotLight.prototype, "angle", {
  39817. get: function () {
  39818. return this._angle;
  39819. },
  39820. set: function (value) {
  39821. this._angle = value;
  39822. this.forceProjectionMatrixCompute();
  39823. },
  39824. enumerable: true,
  39825. configurable: true
  39826. });
  39827. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39828. get: function () {
  39829. return this._shadowAngleScale;
  39830. },
  39831. /**
  39832. * Allows scaling the angle of the light for shadow generation only.
  39833. */
  39834. set: function (value) {
  39835. this._shadowAngleScale = value;
  39836. this.forceProjectionMatrixCompute();
  39837. },
  39838. enumerable: true,
  39839. configurable: true
  39840. });
  39841. /**
  39842. * Returns the string "SpotLight".
  39843. */
  39844. SpotLight.prototype.getClassName = function () {
  39845. return "SpotLight";
  39846. };
  39847. /**
  39848. * Returns the integer 2.
  39849. */
  39850. SpotLight.prototype.getTypeID = function () {
  39851. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39852. };
  39853. /**
  39854. * 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.
  39855. * Returns the SpotLight.
  39856. */
  39857. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39858. var activeCamera = this.getScene().activeCamera;
  39859. if (!activeCamera) {
  39860. return;
  39861. }
  39862. this._shadowAngleScale = this._shadowAngleScale || 1;
  39863. var angle = this._shadowAngleScale * this._angle;
  39864. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39865. };
  39866. SpotLight.prototype._buildUniformLayout = function () {
  39867. this._uniformBuffer.addUniform("vLightData", 4);
  39868. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39869. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39870. this._uniformBuffer.addUniform("vLightDirection", 3);
  39871. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39872. this._uniformBuffer.addUniform("depthValues", 2);
  39873. this._uniformBuffer.create();
  39874. };
  39875. /**
  39876. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39877. * Return the SpotLight.
  39878. */
  39879. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39880. var normalizeDirection;
  39881. if (this.computeTransformedInformation()) {
  39882. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39883. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39884. }
  39885. else {
  39886. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39887. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39888. }
  39889. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39890. return this;
  39891. };
  39892. __decorate([
  39893. BABYLON.serialize()
  39894. ], SpotLight.prototype, "angle", null);
  39895. __decorate([
  39896. BABYLON.serialize()
  39897. /**
  39898. * Allows scaling the angle of the light for shadow generation only.
  39899. */
  39900. ], SpotLight.prototype, "shadowAngleScale", null);
  39901. __decorate([
  39902. BABYLON.serialize()
  39903. ], SpotLight.prototype, "exponent", void 0);
  39904. return SpotLight;
  39905. }(BABYLON.ShadowLight));
  39906. BABYLON.SpotLight = SpotLight;
  39907. })(BABYLON || (BABYLON = {}));
  39908. //# sourceMappingURL=babylon.spotLight.js.map
  39909. var BABYLON;
  39910. (function (BABYLON) {
  39911. var AnimationRange = /** @class */ (function () {
  39912. function AnimationRange(name, from, to) {
  39913. this.name = name;
  39914. this.from = from;
  39915. this.to = to;
  39916. }
  39917. AnimationRange.prototype.clone = function () {
  39918. return new AnimationRange(this.name, this.from, this.to);
  39919. };
  39920. return AnimationRange;
  39921. }());
  39922. BABYLON.AnimationRange = AnimationRange;
  39923. /**
  39924. * Composed of a frame, and an action function
  39925. */
  39926. var AnimationEvent = /** @class */ (function () {
  39927. function AnimationEvent(frame, action, onlyOnce) {
  39928. this.frame = frame;
  39929. this.action = action;
  39930. this.onlyOnce = onlyOnce;
  39931. this.isDone = false;
  39932. }
  39933. return AnimationEvent;
  39934. }());
  39935. BABYLON.AnimationEvent = AnimationEvent;
  39936. var PathCursor = /** @class */ (function () {
  39937. function PathCursor(path) {
  39938. this.path = path;
  39939. this._onchange = new Array();
  39940. this.value = 0;
  39941. this.animations = new Array();
  39942. }
  39943. PathCursor.prototype.getPoint = function () {
  39944. var point = this.path.getPointAtLengthPosition(this.value);
  39945. return new BABYLON.Vector3(point.x, 0, point.y);
  39946. };
  39947. PathCursor.prototype.moveAhead = function (step) {
  39948. if (step === void 0) { step = 0.002; }
  39949. this.move(step);
  39950. return this;
  39951. };
  39952. PathCursor.prototype.moveBack = function (step) {
  39953. if (step === void 0) { step = 0.002; }
  39954. this.move(-step);
  39955. return this;
  39956. };
  39957. PathCursor.prototype.move = function (step) {
  39958. if (Math.abs(step) > 1) {
  39959. throw "step size should be less than 1.";
  39960. }
  39961. this.value += step;
  39962. this.ensureLimits();
  39963. this.raiseOnChange();
  39964. return this;
  39965. };
  39966. PathCursor.prototype.ensureLimits = function () {
  39967. while (this.value > 1) {
  39968. this.value -= 1;
  39969. }
  39970. while (this.value < 0) {
  39971. this.value += 1;
  39972. }
  39973. return this;
  39974. };
  39975. // used by animation engine
  39976. PathCursor.prototype.raiseOnChange = function () {
  39977. var _this = this;
  39978. this._onchange.forEach(function (f) { return f(_this); });
  39979. return this;
  39980. };
  39981. PathCursor.prototype.onchange = function (f) {
  39982. this._onchange.push(f);
  39983. return this;
  39984. };
  39985. return PathCursor;
  39986. }());
  39987. BABYLON.PathCursor = PathCursor;
  39988. var Animation = /** @class */ (function () {
  39989. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39990. this.name = name;
  39991. this.targetProperty = targetProperty;
  39992. this.framePerSecond = framePerSecond;
  39993. this.dataType = dataType;
  39994. this.loopMode = loopMode;
  39995. this.enableBlending = enableBlending;
  39996. this._runtimeAnimations = new Array();
  39997. // The set of event that will be linked to this animation
  39998. this._events = new Array();
  39999. this.blendingSpeed = 0.01;
  40000. this._ranges = {};
  40001. this.targetPropertyPath = targetProperty.split(".");
  40002. this.dataType = dataType;
  40003. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40004. }
  40005. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40006. var dataType = undefined;
  40007. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40008. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40009. }
  40010. else if (from instanceof BABYLON.Quaternion) {
  40011. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40012. }
  40013. else if (from instanceof BABYLON.Vector3) {
  40014. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40015. }
  40016. else if (from instanceof BABYLON.Vector2) {
  40017. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40018. }
  40019. else if (from instanceof BABYLON.Color3) {
  40020. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40021. }
  40022. else if (from instanceof BABYLON.Size) {
  40023. dataType = Animation.ANIMATIONTYPE_SIZE;
  40024. }
  40025. if (dataType == undefined) {
  40026. return null;
  40027. }
  40028. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40029. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40030. animation.setKeys(keys);
  40031. if (easingFunction !== undefined) {
  40032. animation.setEasingFunction(easingFunction);
  40033. }
  40034. return animation;
  40035. };
  40036. /**
  40037. * Sets up an animation.
  40038. * @param property the property to animate
  40039. * @param animationType the animation type to apply
  40040. * @param easingFunction the easing function used in the animation
  40041. * @returns The created animation
  40042. */
  40043. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40044. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40045. animation.setEasingFunction(easingFunction);
  40046. return animation;
  40047. };
  40048. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40049. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40050. if (!animation) {
  40051. return null;
  40052. }
  40053. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40054. };
  40055. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40056. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40057. if (!animation) {
  40058. return null;
  40059. }
  40060. node.animations.push(animation);
  40061. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40062. };
  40063. /**
  40064. * Transition property of the Camera to the target Value.
  40065. * @param property The property to transition
  40066. * @param targetValue The target Value of the property
  40067. * @param host The object where the property to animate belongs
  40068. * @param scene Scene used to run the animation
  40069. * @param frameRate Framerate (in frame/s) to use
  40070. * @param transition The transition type we want to use
  40071. * @param duration The duration of the animation, in milliseconds
  40072. * @param onAnimationEnd Call back trigger at the end of the animation.
  40073. */
  40074. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40075. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40076. if (duration <= 0) {
  40077. host[property] = targetValue;
  40078. if (onAnimationEnd) {
  40079. onAnimationEnd();
  40080. }
  40081. return null;
  40082. }
  40083. var endFrame = frameRate * (duration / 1000);
  40084. transition.setKeys([{
  40085. frame: 0,
  40086. value: host[property].clone ? host[property].clone() : host[property]
  40087. },
  40088. {
  40089. frame: endFrame,
  40090. value: targetValue
  40091. }]);
  40092. if (!host.animations) {
  40093. host.animations = [];
  40094. }
  40095. host.animations.push(transition);
  40096. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40097. animation.onAnimationEnd = onAnimationEnd;
  40098. return animation;
  40099. };
  40100. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40101. /**
  40102. * Return the array of runtime animations currently using this animation
  40103. */
  40104. get: function () {
  40105. return this._runtimeAnimations;
  40106. },
  40107. enumerable: true,
  40108. configurable: true
  40109. });
  40110. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40111. get: function () {
  40112. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40113. var runtimeAnimation = _a[_i];
  40114. if (!runtimeAnimation.isStopped) {
  40115. return true;
  40116. }
  40117. }
  40118. return false;
  40119. },
  40120. enumerable: true,
  40121. configurable: true
  40122. });
  40123. // Methods
  40124. /**
  40125. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40126. */
  40127. Animation.prototype.toString = function (fullDetails) {
  40128. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40129. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40130. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40131. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40132. if (fullDetails) {
  40133. ret += ", Ranges: {";
  40134. var first = true;
  40135. for (var name in this._ranges) {
  40136. if (first) {
  40137. ret += ", ";
  40138. first = false;
  40139. }
  40140. ret += name;
  40141. }
  40142. ret += "}";
  40143. }
  40144. return ret;
  40145. };
  40146. /**
  40147. * Add an event to this animation.
  40148. */
  40149. Animation.prototype.addEvent = function (event) {
  40150. this._events.push(event);
  40151. };
  40152. /**
  40153. * Remove all events found at the given frame
  40154. * @param frame
  40155. */
  40156. Animation.prototype.removeEvents = function (frame) {
  40157. for (var index = 0; index < this._events.length; index++) {
  40158. if (this._events[index].frame === frame) {
  40159. this._events.splice(index, 1);
  40160. index--;
  40161. }
  40162. }
  40163. };
  40164. Animation.prototype.getEvents = function () {
  40165. return this._events;
  40166. };
  40167. Animation.prototype.createRange = function (name, from, to) {
  40168. // check name not already in use; could happen for bones after serialized
  40169. if (!this._ranges[name]) {
  40170. this._ranges[name] = new AnimationRange(name, from, to);
  40171. }
  40172. };
  40173. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40174. if (deleteFrames === void 0) { deleteFrames = true; }
  40175. var range = this._ranges[name];
  40176. if (!range) {
  40177. return;
  40178. }
  40179. if (deleteFrames) {
  40180. var from = range.from;
  40181. var to = range.to;
  40182. // this loop MUST go high to low for multiple splices to work
  40183. for (var key = this._keys.length - 1; key >= 0; key--) {
  40184. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40185. this._keys.splice(key, 1);
  40186. }
  40187. }
  40188. }
  40189. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40190. };
  40191. Animation.prototype.getRange = function (name) {
  40192. return this._ranges[name];
  40193. };
  40194. Animation.prototype.getKeys = function () {
  40195. return this._keys;
  40196. };
  40197. Animation.prototype.getHighestFrame = function () {
  40198. var ret = 0;
  40199. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40200. if (ret < this._keys[key].frame) {
  40201. ret = this._keys[key].frame;
  40202. }
  40203. }
  40204. return ret;
  40205. };
  40206. Animation.prototype.getEasingFunction = function () {
  40207. return this._easingFunction;
  40208. };
  40209. Animation.prototype.setEasingFunction = function (easingFunction) {
  40210. this._easingFunction = easingFunction;
  40211. };
  40212. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40213. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40214. };
  40215. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40216. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40217. };
  40218. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40219. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40220. };
  40221. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40222. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40223. };
  40224. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40225. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40226. };
  40227. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40228. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40229. };
  40230. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40231. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40232. };
  40233. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40234. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40235. };
  40236. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40237. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40238. };
  40239. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40240. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40241. };
  40242. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40243. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40244. };
  40245. Animation.prototype.clone = function () {
  40246. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40247. clone.enableBlending = this.enableBlending;
  40248. clone.blendingSpeed = this.blendingSpeed;
  40249. if (this._keys) {
  40250. clone.setKeys(this._keys);
  40251. }
  40252. if (this._ranges) {
  40253. clone._ranges = {};
  40254. for (var name in this._ranges) {
  40255. var range = this._ranges[name];
  40256. if (!range) {
  40257. continue;
  40258. }
  40259. clone._ranges[name] = range.clone();
  40260. }
  40261. }
  40262. return clone;
  40263. };
  40264. Animation.prototype.setKeys = function (values) {
  40265. this._keys = values.slice(0);
  40266. };
  40267. Animation.prototype.serialize = function () {
  40268. var serializationObject = {};
  40269. serializationObject.name = this.name;
  40270. serializationObject.property = this.targetProperty;
  40271. serializationObject.framePerSecond = this.framePerSecond;
  40272. serializationObject.dataType = this.dataType;
  40273. serializationObject.loopBehavior = this.loopMode;
  40274. serializationObject.enableBlending = this.enableBlending;
  40275. serializationObject.blendingSpeed = this.blendingSpeed;
  40276. var dataType = this.dataType;
  40277. serializationObject.keys = [];
  40278. var keys = this.getKeys();
  40279. for (var index = 0; index < keys.length; index++) {
  40280. var animationKey = keys[index];
  40281. var key = {};
  40282. key.frame = animationKey.frame;
  40283. switch (dataType) {
  40284. case Animation.ANIMATIONTYPE_FLOAT:
  40285. key.values = [animationKey.value];
  40286. break;
  40287. case Animation.ANIMATIONTYPE_QUATERNION:
  40288. case Animation.ANIMATIONTYPE_MATRIX:
  40289. case Animation.ANIMATIONTYPE_VECTOR3:
  40290. case Animation.ANIMATIONTYPE_COLOR3:
  40291. key.values = animationKey.value.asArray();
  40292. break;
  40293. }
  40294. serializationObject.keys.push(key);
  40295. }
  40296. serializationObject.ranges = [];
  40297. for (var name in this._ranges) {
  40298. var source = this._ranges[name];
  40299. if (!source) {
  40300. continue;
  40301. }
  40302. var range = {};
  40303. range.name = name;
  40304. range.from = source.from;
  40305. range.to = source.to;
  40306. serializationObject.ranges.push(range);
  40307. }
  40308. return serializationObject;
  40309. };
  40310. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40311. get: function () {
  40312. return Animation._ANIMATIONTYPE_FLOAT;
  40313. },
  40314. enumerable: true,
  40315. configurable: true
  40316. });
  40317. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40318. get: function () {
  40319. return Animation._ANIMATIONTYPE_VECTOR3;
  40320. },
  40321. enumerable: true,
  40322. configurable: true
  40323. });
  40324. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40325. get: function () {
  40326. return Animation._ANIMATIONTYPE_VECTOR2;
  40327. },
  40328. enumerable: true,
  40329. configurable: true
  40330. });
  40331. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40332. get: function () {
  40333. return Animation._ANIMATIONTYPE_SIZE;
  40334. },
  40335. enumerable: true,
  40336. configurable: true
  40337. });
  40338. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40339. get: function () {
  40340. return Animation._ANIMATIONTYPE_QUATERNION;
  40341. },
  40342. enumerable: true,
  40343. configurable: true
  40344. });
  40345. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40346. get: function () {
  40347. return Animation._ANIMATIONTYPE_MATRIX;
  40348. },
  40349. enumerable: true,
  40350. configurable: true
  40351. });
  40352. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40353. get: function () {
  40354. return Animation._ANIMATIONTYPE_COLOR3;
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40360. get: function () {
  40361. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40362. },
  40363. enumerable: true,
  40364. configurable: true
  40365. });
  40366. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40367. get: function () {
  40368. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40369. },
  40370. enumerable: true,
  40371. configurable: true
  40372. });
  40373. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40374. get: function () {
  40375. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40376. },
  40377. enumerable: true,
  40378. configurable: true
  40379. });
  40380. Animation.Parse = function (parsedAnimation) {
  40381. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40382. var dataType = parsedAnimation.dataType;
  40383. var keys = [];
  40384. var data;
  40385. var index;
  40386. if (parsedAnimation.enableBlending) {
  40387. animation.enableBlending = parsedAnimation.enableBlending;
  40388. }
  40389. if (parsedAnimation.blendingSpeed) {
  40390. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40391. }
  40392. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40393. var key = parsedAnimation.keys[index];
  40394. var inTangent;
  40395. var outTangent;
  40396. switch (dataType) {
  40397. case Animation.ANIMATIONTYPE_FLOAT:
  40398. data = key.values[0];
  40399. if (key.values.length >= 1) {
  40400. inTangent = key.values[1];
  40401. }
  40402. if (key.values.length >= 2) {
  40403. outTangent = key.values[2];
  40404. }
  40405. break;
  40406. case Animation.ANIMATIONTYPE_QUATERNION:
  40407. data = BABYLON.Quaternion.FromArray(key.values);
  40408. if (key.values.length >= 8) {
  40409. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40410. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40411. inTangent = _inTangent;
  40412. }
  40413. }
  40414. if (key.values.length >= 12) {
  40415. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40416. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40417. outTangent = _outTangent;
  40418. }
  40419. }
  40420. break;
  40421. case Animation.ANIMATIONTYPE_MATRIX:
  40422. data = BABYLON.Matrix.FromArray(key.values);
  40423. break;
  40424. case Animation.ANIMATIONTYPE_COLOR3:
  40425. data = BABYLON.Color3.FromArray(key.values);
  40426. break;
  40427. case Animation.ANIMATIONTYPE_VECTOR3:
  40428. default:
  40429. data = BABYLON.Vector3.FromArray(key.values);
  40430. break;
  40431. }
  40432. var keyData = {};
  40433. keyData.frame = key.frame;
  40434. keyData.value = data;
  40435. if (inTangent != undefined) {
  40436. keyData.inTangent = inTangent;
  40437. }
  40438. if (outTangent != undefined) {
  40439. keyData.outTangent = outTangent;
  40440. }
  40441. keys.push(keyData);
  40442. }
  40443. animation.setKeys(keys);
  40444. if (parsedAnimation.ranges) {
  40445. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40446. data = parsedAnimation.ranges[index];
  40447. animation.createRange(data.name, data.from, data.to);
  40448. }
  40449. }
  40450. return animation;
  40451. };
  40452. Animation.AppendSerializedAnimations = function (source, destination) {
  40453. if (source.animations) {
  40454. destination.animations = [];
  40455. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40456. var animation = source.animations[animationIndex];
  40457. destination.animations.push(animation.serialize());
  40458. }
  40459. }
  40460. };
  40461. Animation.AllowMatricesInterpolation = false;
  40462. // Statics
  40463. Animation._ANIMATIONTYPE_FLOAT = 0;
  40464. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40465. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40466. Animation._ANIMATIONTYPE_MATRIX = 3;
  40467. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40468. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40469. Animation._ANIMATIONTYPE_SIZE = 6;
  40470. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40471. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40472. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40473. return Animation;
  40474. }());
  40475. BABYLON.Animation = Animation;
  40476. })(BABYLON || (BABYLON = {}));
  40477. //# sourceMappingURL=babylon.animation.js.map
  40478. var BABYLON;
  40479. (function (BABYLON) {
  40480. var RuntimeAnimation = /** @class */ (function () {
  40481. function RuntimeAnimation(target, animation) {
  40482. this._offsetsCache = {};
  40483. this._highLimitsCache = {};
  40484. this._stopped = false;
  40485. this._blendingFactor = 0;
  40486. this._ratioOffset = 0;
  40487. this._animation = animation;
  40488. this._target = target;
  40489. animation._runtimeAnimations.push(this);
  40490. }
  40491. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40492. get: function () {
  40493. return this._animation;
  40494. },
  40495. enumerable: true,
  40496. configurable: true
  40497. });
  40498. RuntimeAnimation.prototype.reset = function () {
  40499. this._offsetsCache = {};
  40500. this._highLimitsCache = {};
  40501. this.currentFrame = 0;
  40502. this._blendingFactor = 0;
  40503. this._originalBlendValue = null;
  40504. };
  40505. RuntimeAnimation.prototype.isStopped = function () {
  40506. return this._stopped;
  40507. };
  40508. RuntimeAnimation.prototype.dispose = function () {
  40509. var index = this._animation.runtimeAnimations.indexOf(this);
  40510. if (index > -1) {
  40511. this._animation.runtimeAnimations.splice(index, 1);
  40512. }
  40513. };
  40514. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40515. if (typeof value === "function") {
  40516. return value();
  40517. }
  40518. return value;
  40519. };
  40520. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40521. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40522. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40523. }
  40524. this.currentFrame = currentFrame;
  40525. var keys = this._animation.getKeys();
  40526. // Try to get a hash to find the right key
  40527. 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));
  40528. if (keys[startKeyIndex].frame >= currentFrame) {
  40529. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40530. startKeyIndex--;
  40531. }
  40532. }
  40533. for (var key = startKeyIndex; key < keys.length; key++) {
  40534. var endKey = keys[key + 1];
  40535. if (endKey.frame >= currentFrame) {
  40536. var startKey = keys[key];
  40537. var startValue = this._getKeyValue(startKey.value);
  40538. var endValue = this._getKeyValue(endKey.value);
  40539. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40540. var frameDelta = endKey.frame - startKey.frame;
  40541. // gradient : percent of currentFrame between the frame inf and the frame sup
  40542. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40543. // check for easingFunction and correction of gradient
  40544. var easingFunction = this._animation.getEasingFunction();
  40545. if (easingFunction != null) {
  40546. gradient = easingFunction.ease(gradient);
  40547. }
  40548. switch (this._animation.dataType) {
  40549. // Float
  40550. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40551. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40552. switch (loopMode) {
  40553. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40554. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40555. return floatValue;
  40556. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40557. return offsetValue * repeatCount + floatValue;
  40558. }
  40559. break;
  40560. // Quaternion
  40561. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40562. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40563. switch (loopMode) {
  40564. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40565. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40566. return quatValue;
  40567. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40568. return quatValue.add(offsetValue.scale(repeatCount));
  40569. }
  40570. return quatValue;
  40571. // Vector3
  40572. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40573. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40574. switch (loopMode) {
  40575. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40576. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40577. return vec3Value;
  40578. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40579. return vec3Value.add(offsetValue.scale(repeatCount));
  40580. }
  40581. // Vector2
  40582. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40583. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40584. switch (loopMode) {
  40585. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40586. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40587. return vec2Value;
  40588. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40589. return vec2Value.add(offsetValue.scale(repeatCount));
  40590. }
  40591. // Size
  40592. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40593. switch (loopMode) {
  40594. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40595. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40596. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40597. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40598. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40599. }
  40600. // Color3
  40601. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40602. switch (loopMode) {
  40603. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40604. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40605. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40606. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40607. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40608. }
  40609. // Matrix
  40610. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40611. switch (loopMode) {
  40612. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40613. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40614. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40615. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40616. }
  40617. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40618. return startValue;
  40619. }
  40620. default:
  40621. break;
  40622. }
  40623. break;
  40624. }
  40625. }
  40626. return this._getKeyValue(keys[keys.length - 1].value);
  40627. };
  40628. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40629. if (blend === void 0) { blend = false; }
  40630. // Set value
  40631. var path;
  40632. var destination;
  40633. var targetPropertyPath = this._animation.targetPropertyPath;
  40634. if (targetPropertyPath.length > 1) {
  40635. var property = this._target[targetPropertyPath[0]];
  40636. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40637. property = property[targetPropertyPath[index]];
  40638. }
  40639. path = targetPropertyPath[targetPropertyPath.length - 1];
  40640. destination = property;
  40641. }
  40642. else {
  40643. path = targetPropertyPath[0];
  40644. destination = this._target;
  40645. }
  40646. // Blending
  40647. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40648. if (!this._originalBlendValue) {
  40649. if (destination[path].clone) {
  40650. this._originalBlendValue = destination[path].clone();
  40651. }
  40652. else {
  40653. this._originalBlendValue = destination[path];
  40654. }
  40655. }
  40656. if (this._originalBlendValue.prototype) {
  40657. if (this._originalBlendValue.prototype.Lerp) {
  40658. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40659. }
  40660. else {
  40661. destination[path] = currentValue;
  40662. }
  40663. }
  40664. else if (this._originalBlendValue.m) {
  40665. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40666. }
  40667. else {
  40668. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40669. }
  40670. this._blendingFactor += this._animation.blendingSpeed;
  40671. }
  40672. else {
  40673. destination[path] = currentValue;
  40674. }
  40675. if (this._target.markAsDirty) {
  40676. this._target.markAsDirty(this._animation.targetProperty);
  40677. }
  40678. };
  40679. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40680. var keys = this._animation.getKeys();
  40681. if (frame < keys[0].frame) {
  40682. frame = keys[0].frame;
  40683. }
  40684. else if (frame > keys[keys.length - 1].frame) {
  40685. frame = keys[keys.length - 1].frame;
  40686. }
  40687. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40688. this.setValue(currentValue);
  40689. };
  40690. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40691. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40692. this._ratioOffset = this._previousRatio - newRatio;
  40693. };
  40694. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40695. if (blend === void 0) { blend = false; }
  40696. var targetPropertyPath = this._animation.targetPropertyPath;
  40697. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40698. this._stopped = true;
  40699. return false;
  40700. }
  40701. var returnValue = true;
  40702. var keys = this._animation.getKeys();
  40703. // Adding a start key at frame 0 if missing
  40704. if (keys[0].frame !== 0) {
  40705. var newKey = { frame: 0, value: keys[0].value };
  40706. keys.splice(0, 0, newKey);
  40707. }
  40708. // Check limits
  40709. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40710. from = keys[0].frame;
  40711. }
  40712. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40713. to = keys[keys.length - 1].frame;
  40714. }
  40715. //to and from cannot be the same key
  40716. if (from === to) {
  40717. if (from > keys[0].frame) {
  40718. from--;
  40719. }
  40720. else if (to < keys[keys.length - 1].frame) {
  40721. to++;
  40722. }
  40723. }
  40724. // Compute ratio
  40725. var range = to - from;
  40726. var offsetValue;
  40727. // ratio represents the frame delta between from and to
  40728. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40729. var highLimitValue = 0;
  40730. this._previousDelay = delay;
  40731. this._previousRatio = ratio;
  40732. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40733. returnValue = false;
  40734. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40735. }
  40736. else {
  40737. // Get max value if required
  40738. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40739. var keyOffset = to.toString() + from.toString();
  40740. if (!this._offsetsCache[keyOffset]) {
  40741. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40742. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40743. switch (this._animation.dataType) {
  40744. // Float
  40745. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40746. this._offsetsCache[keyOffset] = toValue - fromValue;
  40747. break;
  40748. // Quaternion
  40749. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40750. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40751. break;
  40752. // Vector3
  40753. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40754. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40755. // Vector2
  40756. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40757. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40758. // Size
  40759. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40760. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40761. // Color3
  40762. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40763. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40764. default:
  40765. break;
  40766. }
  40767. this._highLimitsCache[keyOffset] = toValue;
  40768. }
  40769. highLimitValue = this._highLimitsCache[keyOffset];
  40770. offsetValue = this._offsetsCache[keyOffset];
  40771. }
  40772. }
  40773. if (offsetValue === undefined) {
  40774. switch (this._animation.dataType) {
  40775. // Float
  40776. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40777. offsetValue = 0;
  40778. break;
  40779. // Quaternion
  40780. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40781. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40782. break;
  40783. // Vector3
  40784. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40785. offsetValue = BABYLON.Vector3.Zero();
  40786. break;
  40787. // Vector2
  40788. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40789. offsetValue = BABYLON.Vector2.Zero();
  40790. break;
  40791. // Size
  40792. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40793. offsetValue = BABYLON.Size.Zero();
  40794. break;
  40795. // Color3
  40796. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40797. offsetValue = BABYLON.Color3.Black();
  40798. }
  40799. }
  40800. // Compute value
  40801. var repeatCount = (ratio / range) >> 0;
  40802. var currentFrame = returnValue ? from + ratio % range : to;
  40803. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40804. // Set value
  40805. this.setValue(currentValue);
  40806. // Check events
  40807. var events = this._animation.getEvents();
  40808. for (var index = 0; index < events.length; index++) {
  40809. // Make sure current frame has passed event frame and that event frame is within the current range
  40810. // Also, handle both forward and reverse animations
  40811. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40812. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40813. var event = events[index];
  40814. if (!event.isDone) {
  40815. // If event should be done only once, remove it.
  40816. if (event.onlyOnce) {
  40817. events.splice(index, 1);
  40818. index--;
  40819. }
  40820. event.isDone = true;
  40821. event.action();
  40822. } // Don't do anything if the event has already be done.
  40823. }
  40824. else if (events[index].isDone && !events[index].onlyOnce) {
  40825. // reset event, the animation is looping
  40826. events[index].isDone = false;
  40827. }
  40828. }
  40829. if (!returnValue) {
  40830. this._stopped = true;
  40831. }
  40832. return returnValue;
  40833. };
  40834. return RuntimeAnimation;
  40835. }());
  40836. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40837. })(BABYLON || (BABYLON = {}));
  40838. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40839. var BABYLON;
  40840. (function (BABYLON) {
  40841. var Animatable = /** @class */ (function () {
  40842. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40843. if (fromFrame === void 0) { fromFrame = 0; }
  40844. if (toFrame === void 0) { toFrame = 100; }
  40845. if (loopAnimation === void 0) { loopAnimation = false; }
  40846. if (speedRatio === void 0) { speedRatio = 1.0; }
  40847. this.target = target;
  40848. this.fromFrame = fromFrame;
  40849. this.toFrame = toFrame;
  40850. this.loopAnimation = loopAnimation;
  40851. this.onAnimationEnd = onAnimationEnd;
  40852. this._localDelayOffset = null;
  40853. this._pausedDelay = null;
  40854. this._runtimeAnimations = new Array();
  40855. this._paused = false;
  40856. this._speedRatio = 1;
  40857. this.animationStarted = false;
  40858. if (animations) {
  40859. this.appendAnimations(target, animations);
  40860. }
  40861. this._speedRatio = speedRatio;
  40862. this._scene = scene;
  40863. scene._activeAnimatables.push(this);
  40864. }
  40865. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40866. get: function () {
  40867. return this._speedRatio;
  40868. },
  40869. set: function (value) {
  40870. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40871. var animation = this._runtimeAnimations[index];
  40872. animation._prepareForSpeedRatioChange(value);
  40873. }
  40874. this._speedRatio = value;
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. // Methods
  40880. Animatable.prototype.getAnimations = function () {
  40881. return this._runtimeAnimations;
  40882. };
  40883. Animatable.prototype.appendAnimations = function (target, animations) {
  40884. for (var index = 0; index < animations.length; index++) {
  40885. var animation = animations[index];
  40886. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40887. }
  40888. };
  40889. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40890. var runtimeAnimations = this._runtimeAnimations;
  40891. for (var index = 0; index < runtimeAnimations.length; index++) {
  40892. if (runtimeAnimations[index].animation.targetProperty === property) {
  40893. return runtimeAnimations[index].animation;
  40894. }
  40895. }
  40896. return null;
  40897. };
  40898. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40899. var runtimeAnimations = this._runtimeAnimations;
  40900. for (var index = 0; index < runtimeAnimations.length; index++) {
  40901. if (runtimeAnimations[index].animation.targetProperty === property) {
  40902. return runtimeAnimations[index];
  40903. }
  40904. }
  40905. return null;
  40906. };
  40907. Animatable.prototype.reset = function () {
  40908. var runtimeAnimations = this._runtimeAnimations;
  40909. for (var index = 0; index < runtimeAnimations.length; index++) {
  40910. runtimeAnimations[index].reset();
  40911. }
  40912. this._localDelayOffset = null;
  40913. this._pausedDelay = null;
  40914. };
  40915. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40916. var runtimeAnimations = this._runtimeAnimations;
  40917. for (var index = 0; index < runtimeAnimations.length; index++) {
  40918. runtimeAnimations[index].animation.enableBlending = true;
  40919. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40920. }
  40921. };
  40922. Animatable.prototype.disableBlending = function () {
  40923. var runtimeAnimations = this._runtimeAnimations;
  40924. for (var index = 0; index < runtimeAnimations.length; index++) {
  40925. runtimeAnimations[index].animation.enableBlending = false;
  40926. }
  40927. };
  40928. Animatable.prototype.goToFrame = function (frame) {
  40929. var runtimeAnimations = this._runtimeAnimations;
  40930. if (runtimeAnimations[0]) {
  40931. var fps = runtimeAnimations[0].animation.framePerSecond;
  40932. var currentFrame = runtimeAnimations[0].currentFrame;
  40933. var adjustTime = frame - currentFrame;
  40934. var delay = adjustTime * 1000 / fps;
  40935. if (this._localDelayOffset === null) {
  40936. this._localDelayOffset = 0;
  40937. }
  40938. this._localDelayOffset -= delay;
  40939. }
  40940. for (var index = 0; index < runtimeAnimations.length; index++) {
  40941. runtimeAnimations[index].goToFrame(frame);
  40942. }
  40943. };
  40944. Animatable.prototype.pause = function () {
  40945. if (this._paused) {
  40946. return;
  40947. }
  40948. this._paused = true;
  40949. };
  40950. Animatable.prototype.restart = function () {
  40951. this._paused = false;
  40952. };
  40953. Animatable.prototype.stop = function (animationName) {
  40954. if (animationName) {
  40955. var idx = this._scene._activeAnimatables.indexOf(this);
  40956. if (idx > -1) {
  40957. var runtimeAnimations = this._runtimeAnimations;
  40958. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40959. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40960. continue;
  40961. }
  40962. runtimeAnimations[index].dispose();
  40963. runtimeAnimations.splice(index, 1);
  40964. }
  40965. if (runtimeAnimations.length == 0) {
  40966. this._scene._activeAnimatables.splice(idx, 1);
  40967. if (this.onAnimationEnd) {
  40968. this.onAnimationEnd();
  40969. }
  40970. }
  40971. }
  40972. }
  40973. else {
  40974. var index = this._scene._activeAnimatables.indexOf(this);
  40975. if (index > -1) {
  40976. this._scene._activeAnimatables.splice(index, 1);
  40977. var runtimeAnimations = this._runtimeAnimations;
  40978. for (var index = 0; index < runtimeAnimations.length; index++) {
  40979. runtimeAnimations[index].dispose();
  40980. }
  40981. if (this.onAnimationEnd) {
  40982. this.onAnimationEnd();
  40983. }
  40984. }
  40985. }
  40986. };
  40987. Animatable.prototype._animate = function (delay) {
  40988. if (this._paused) {
  40989. this.animationStarted = false;
  40990. if (this._pausedDelay === null) {
  40991. this._pausedDelay = delay;
  40992. }
  40993. return true;
  40994. }
  40995. if (this._localDelayOffset === null) {
  40996. this._localDelayOffset = delay;
  40997. }
  40998. else if (this._pausedDelay !== null) {
  40999. this._localDelayOffset += delay - this._pausedDelay;
  41000. this._pausedDelay = null;
  41001. }
  41002. // Animating
  41003. var running = false;
  41004. var runtimeAnimations = this._runtimeAnimations;
  41005. var index;
  41006. for (index = 0; index < runtimeAnimations.length; index++) {
  41007. var animation = runtimeAnimations[index];
  41008. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41009. running = running || isRunning;
  41010. }
  41011. this.animationStarted = running;
  41012. if (!running) {
  41013. // Remove from active animatables
  41014. index = this._scene._activeAnimatables.indexOf(this);
  41015. this._scene._activeAnimatables.splice(index, 1);
  41016. // Dispose all runtime animations
  41017. for (index = 0; index < runtimeAnimations.length; index++) {
  41018. runtimeAnimations[index].dispose();
  41019. }
  41020. }
  41021. if (!running && this.onAnimationEnd) {
  41022. this.onAnimationEnd();
  41023. this.onAnimationEnd = null;
  41024. }
  41025. return running;
  41026. };
  41027. return Animatable;
  41028. }());
  41029. BABYLON.Animatable = Animatable;
  41030. })(BABYLON || (BABYLON = {}));
  41031. //# sourceMappingURL=babylon.animatable.js.map
  41032. var BABYLON;
  41033. (function (BABYLON) {
  41034. var EasingFunction = /** @class */ (function () {
  41035. function EasingFunction() {
  41036. // Properties
  41037. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41038. }
  41039. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41040. get: function () {
  41041. return EasingFunction._EASINGMODE_EASEIN;
  41042. },
  41043. enumerable: true,
  41044. configurable: true
  41045. });
  41046. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41047. get: function () {
  41048. return EasingFunction._EASINGMODE_EASEOUT;
  41049. },
  41050. enumerable: true,
  41051. configurable: true
  41052. });
  41053. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41054. get: function () {
  41055. return EasingFunction._EASINGMODE_EASEINOUT;
  41056. },
  41057. enumerable: true,
  41058. configurable: true
  41059. });
  41060. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41061. var n = Math.min(Math.max(easingMode, 0), 2);
  41062. this._easingMode = n;
  41063. };
  41064. EasingFunction.prototype.getEasingMode = function () {
  41065. return this._easingMode;
  41066. };
  41067. EasingFunction.prototype.easeInCore = function (gradient) {
  41068. throw new Error('You must implement this method');
  41069. };
  41070. EasingFunction.prototype.ease = function (gradient) {
  41071. switch (this._easingMode) {
  41072. case EasingFunction.EASINGMODE_EASEIN:
  41073. return this.easeInCore(gradient);
  41074. case EasingFunction.EASINGMODE_EASEOUT:
  41075. return (1 - this.easeInCore(1 - gradient));
  41076. }
  41077. if (gradient >= 0.5) {
  41078. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41079. }
  41080. return (this.easeInCore(gradient * 2) * 0.5);
  41081. };
  41082. //Statics
  41083. EasingFunction._EASINGMODE_EASEIN = 0;
  41084. EasingFunction._EASINGMODE_EASEOUT = 1;
  41085. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41086. return EasingFunction;
  41087. }());
  41088. BABYLON.EasingFunction = EasingFunction;
  41089. var CircleEase = /** @class */ (function (_super) {
  41090. __extends(CircleEase, _super);
  41091. function CircleEase() {
  41092. return _super !== null && _super.apply(this, arguments) || this;
  41093. }
  41094. CircleEase.prototype.easeInCore = function (gradient) {
  41095. gradient = Math.max(0, Math.min(1, gradient));
  41096. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41097. };
  41098. return CircleEase;
  41099. }(EasingFunction));
  41100. BABYLON.CircleEase = CircleEase;
  41101. var BackEase = /** @class */ (function (_super) {
  41102. __extends(BackEase, _super);
  41103. function BackEase(amplitude) {
  41104. if (amplitude === void 0) { amplitude = 1; }
  41105. var _this = _super.call(this) || this;
  41106. _this.amplitude = amplitude;
  41107. return _this;
  41108. }
  41109. BackEase.prototype.easeInCore = function (gradient) {
  41110. var num = Math.max(0, this.amplitude);
  41111. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41112. };
  41113. return BackEase;
  41114. }(EasingFunction));
  41115. BABYLON.BackEase = BackEase;
  41116. var BounceEase = /** @class */ (function (_super) {
  41117. __extends(BounceEase, _super);
  41118. function BounceEase(bounces, bounciness) {
  41119. if (bounces === void 0) { bounces = 3; }
  41120. if (bounciness === void 0) { bounciness = 2; }
  41121. var _this = _super.call(this) || this;
  41122. _this.bounces = bounces;
  41123. _this.bounciness = bounciness;
  41124. return _this;
  41125. }
  41126. BounceEase.prototype.easeInCore = function (gradient) {
  41127. var y = Math.max(0.0, this.bounces);
  41128. var bounciness = this.bounciness;
  41129. if (bounciness <= 1.0) {
  41130. bounciness = 1.001;
  41131. }
  41132. var num9 = Math.pow(bounciness, y);
  41133. var num5 = 1.0 - bounciness;
  41134. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41135. var num15 = gradient * num4;
  41136. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41137. var num3 = Math.floor(num65);
  41138. var num13 = num3 + 1.0;
  41139. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41140. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41141. var num7 = (num8 + num12) * 0.5;
  41142. var num6 = gradient - num7;
  41143. var num2 = num7 - num8;
  41144. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41145. };
  41146. return BounceEase;
  41147. }(EasingFunction));
  41148. BABYLON.BounceEase = BounceEase;
  41149. var CubicEase = /** @class */ (function (_super) {
  41150. __extends(CubicEase, _super);
  41151. function CubicEase() {
  41152. return _super !== null && _super.apply(this, arguments) || this;
  41153. }
  41154. CubicEase.prototype.easeInCore = function (gradient) {
  41155. return (gradient * gradient * gradient);
  41156. };
  41157. return CubicEase;
  41158. }(EasingFunction));
  41159. BABYLON.CubicEase = CubicEase;
  41160. var ElasticEase = /** @class */ (function (_super) {
  41161. __extends(ElasticEase, _super);
  41162. function ElasticEase(oscillations, springiness) {
  41163. if (oscillations === void 0) { oscillations = 3; }
  41164. if (springiness === void 0) { springiness = 3; }
  41165. var _this = _super.call(this) || this;
  41166. _this.oscillations = oscillations;
  41167. _this.springiness = springiness;
  41168. return _this;
  41169. }
  41170. ElasticEase.prototype.easeInCore = function (gradient) {
  41171. var num2;
  41172. var num3 = Math.max(0.0, this.oscillations);
  41173. var num = Math.max(0.0, this.springiness);
  41174. if (num == 0) {
  41175. num2 = gradient;
  41176. }
  41177. else {
  41178. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41179. }
  41180. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41181. };
  41182. return ElasticEase;
  41183. }(EasingFunction));
  41184. BABYLON.ElasticEase = ElasticEase;
  41185. var ExponentialEase = /** @class */ (function (_super) {
  41186. __extends(ExponentialEase, _super);
  41187. function ExponentialEase(exponent) {
  41188. if (exponent === void 0) { exponent = 2; }
  41189. var _this = _super.call(this) || this;
  41190. _this.exponent = exponent;
  41191. return _this;
  41192. }
  41193. ExponentialEase.prototype.easeInCore = function (gradient) {
  41194. if (this.exponent <= 0) {
  41195. return gradient;
  41196. }
  41197. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41198. };
  41199. return ExponentialEase;
  41200. }(EasingFunction));
  41201. BABYLON.ExponentialEase = ExponentialEase;
  41202. var PowerEase = /** @class */ (function (_super) {
  41203. __extends(PowerEase, _super);
  41204. function PowerEase(power) {
  41205. if (power === void 0) { power = 2; }
  41206. var _this = _super.call(this) || this;
  41207. _this.power = power;
  41208. return _this;
  41209. }
  41210. PowerEase.prototype.easeInCore = function (gradient) {
  41211. var y = Math.max(0.0, this.power);
  41212. return Math.pow(gradient, y);
  41213. };
  41214. return PowerEase;
  41215. }(EasingFunction));
  41216. BABYLON.PowerEase = PowerEase;
  41217. var QuadraticEase = /** @class */ (function (_super) {
  41218. __extends(QuadraticEase, _super);
  41219. function QuadraticEase() {
  41220. return _super !== null && _super.apply(this, arguments) || this;
  41221. }
  41222. QuadraticEase.prototype.easeInCore = function (gradient) {
  41223. return (gradient * gradient);
  41224. };
  41225. return QuadraticEase;
  41226. }(EasingFunction));
  41227. BABYLON.QuadraticEase = QuadraticEase;
  41228. var QuarticEase = /** @class */ (function (_super) {
  41229. __extends(QuarticEase, _super);
  41230. function QuarticEase() {
  41231. return _super !== null && _super.apply(this, arguments) || this;
  41232. }
  41233. QuarticEase.prototype.easeInCore = function (gradient) {
  41234. return (gradient * gradient * gradient * gradient);
  41235. };
  41236. return QuarticEase;
  41237. }(EasingFunction));
  41238. BABYLON.QuarticEase = QuarticEase;
  41239. var QuinticEase = /** @class */ (function (_super) {
  41240. __extends(QuinticEase, _super);
  41241. function QuinticEase() {
  41242. return _super !== null && _super.apply(this, arguments) || this;
  41243. }
  41244. QuinticEase.prototype.easeInCore = function (gradient) {
  41245. return (gradient * gradient * gradient * gradient * gradient);
  41246. };
  41247. return QuinticEase;
  41248. }(EasingFunction));
  41249. BABYLON.QuinticEase = QuinticEase;
  41250. var SineEase = /** @class */ (function (_super) {
  41251. __extends(SineEase, _super);
  41252. function SineEase() {
  41253. return _super !== null && _super.apply(this, arguments) || this;
  41254. }
  41255. SineEase.prototype.easeInCore = function (gradient) {
  41256. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41257. };
  41258. return SineEase;
  41259. }(EasingFunction));
  41260. BABYLON.SineEase = SineEase;
  41261. var BezierCurveEase = /** @class */ (function (_super) {
  41262. __extends(BezierCurveEase, _super);
  41263. function BezierCurveEase(x1, y1, x2, y2) {
  41264. if (x1 === void 0) { x1 = 0; }
  41265. if (y1 === void 0) { y1 = 0; }
  41266. if (x2 === void 0) { x2 = 1; }
  41267. if (y2 === void 0) { y2 = 1; }
  41268. var _this = _super.call(this) || this;
  41269. _this.x1 = x1;
  41270. _this.y1 = y1;
  41271. _this.x2 = x2;
  41272. _this.y2 = y2;
  41273. return _this;
  41274. }
  41275. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41276. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41277. };
  41278. return BezierCurveEase;
  41279. }(EasingFunction));
  41280. BABYLON.BezierCurveEase = BezierCurveEase;
  41281. })(BABYLON || (BABYLON = {}));
  41282. //# sourceMappingURL=babylon.easing.js.map
  41283. var BABYLON;
  41284. (function (BABYLON) {
  41285. var Condition = /** @class */ (function () {
  41286. function Condition(actionManager) {
  41287. this._actionManager = actionManager;
  41288. }
  41289. Condition.prototype.isValid = function () {
  41290. return true;
  41291. };
  41292. Condition.prototype._getProperty = function (propertyPath) {
  41293. return this._actionManager._getProperty(propertyPath);
  41294. };
  41295. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41296. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41297. };
  41298. Condition.prototype.serialize = function () {
  41299. };
  41300. Condition.prototype._serialize = function (serializedCondition) {
  41301. return {
  41302. type: 2,
  41303. children: [],
  41304. name: serializedCondition.name,
  41305. properties: serializedCondition.properties
  41306. };
  41307. };
  41308. return Condition;
  41309. }());
  41310. BABYLON.Condition = Condition;
  41311. var ValueCondition = /** @class */ (function (_super) {
  41312. __extends(ValueCondition, _super);
  41313. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41314. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41315. var _this = _super.call(this, actionManager) || this;
  41316. _this.propertyPath = propertyPath;
  41317. _this.value = value;
  41318. _this.operator = operator;
  41319. _this._target = target;
  41320. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41321. _this._property = _this._getProperty(_this.propertyPath);
  41322. return _this;
  41323. }
  41324. Object.defineProperty(ValueCondition, "IsEqual", {
  41325. get: function () {
  41326. return ValueCondition._IsEqual;
  41327. },
  41328. enumerable: true,
  41329. configurable: true
  41330. });
  41331. Object.defineProperty(ValueCondition, "IsDifferent", {
  41332. get: function () {
  41333. return ValueCondition._IsDifferent;
  41334. },
  41335. enumerable: true,
  41336. configurable: true
  41337. });
  41338. Object.defineProperty(ValueCondition, "IsGreater", {
  41339. get: function () {
  41340. return ValueCondition._IsGreater;
  41341. },
  41342. enumerable: true,
  41343. configurable: true
  41344. });
  41345. Object.defineProperty(ValueCondition, "IsLesser", {
  41346. get: function () {
  41347. return ValueCondition._IsLesser;
  41348. },
  41349. enumerable: true,
  41350. configurable: true
  41351. });
  41352. // Methods
  41353. ValueCondition.prototype.isValid = function () {
  41354. switch (this.operator) {
  41355. case ValueCondition.IsGreater:
  41356. return this._effectiveTarget[this._property] > this.value;
  41357. case ValueCondition.IsLesser:
  41358. return this._effectiveTarget[this._property] < this.value;
  41359. case ValueCondition.IsEqual:
  41360. case ValueCondition.IsDifferent:
  41361. var check;
  41362. if (this.value.equals) {
  41363. check = this.value.equals(this._effectiveTarget[this._property]);
  41364. }
  41365. else {
  41366. check = this.value === this._effectiveTarget[this._property];
  41367. }
  41368. return this.operator === ValueCondition.IsEqual ? check : !check;
  41369. }
  41370. return false;
  41371. };
  41372. ValueCondition.prototype.serialize = function () {
  41373. return this._serialize({
  41374. name: "ValueCondition",
  41375. properties: [
  41376. BABYLON.Action._GetTargetProperty(this._target),
  41377. { name: "propertyPath", value: this.propertyPath },
  41378. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41379. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41380. ]
  41381. });
  41382. };
  41383. ValueCondition.GetOperatorName = function (operator) {
  41384. switch (operator) {
  41385. case ValueCondition._IsEqual: return "IsEqual";
  41386. case ValueCondition._IsDifferent: return "IsDifferent";
  41387. case ValueCondition._IsGreater: return "IsGreater";
  41388. case ValueCondition._IsLesser: return "IsLesser";
  41389. default: return "";
  41390. }
  41391. };
  41392. // Statics
  41393. ValueCondition._IsEqual = 0;
  41394. ValueCondition._IsDifferent = 1;
  41395. ValueCondition._IsGreater = 2;
  41396. ValueCondition._IsLesser = 3;
  41397. return ValueCondition;
  41398. }(Condition));
  41399. BABYLON.ValueCondition = ValueCondition;
  41400. var PredicateCondition = /** @class */ (function (_super) {
  41401. __extends(PredicateCondition, _super);
  41402. function PredicateCondition(actionManager, predicate) {
  41403. var _this = _super.call(this, actionManager) || this;
  41404. _this.predicate = predicate;
  41405. return _this;
  41406. }
  41407. PredicateCondition.prototype.isValid = function () {
  41408. return this.predicate();
  41409. };
  41410. return PredicateCondition;
  41411. }(Condition));
  41412. BABYLON.PredicateCondition = PredicateCondition;
  41413. var StateCondition = /** @class */ (function (_super) {
  41414. __extends(StateCondition, _super);
  41415. function StateCondition(actionManager, target, value) {
  41416. var _this = _super.call(this, actionManager) || this;
  41417. _this.value = value;
  41418. _this._target = target;
  41419. return _this;
  41420. }
  41421. // Methods
  41422. StateCondition.prototype.isValid = function () {
  41423. return this._target.state === this.value;
  41424. };
  41425. StateCondition.prototype.serialize = function () {
  41426. return this._serialize({
  41427. name: "StateCondition",
  41428. properties: [
  41429. BABYLON.Action._GetTargetProperty(this._target),
  41430. { name: "value", value: this.value }
  41431. ]
  41432. });
  41433. };
  41434. return StateCondition;
  41435. }(Condition));
  41436. BABYLON.StateCondition = StateCondition;
  41437. })(BABYLON || (BABYLON = {}));
  41438. //# sourceMappingURL=babylon.condition.js.map
  41439. var BABYLON;
  41440. (function (BABYLON) {
  41441. var Action = /** @class */ (function () {
  41442. function Action(triggerOptions, condition) {
  41443. this.triggerOptions = triggerOptions;
  41444. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41445. if (triggerOptions.parameter) {
  41446. this.trigger = triggerOptions.trigger;
  41447. this._triggerParameter = triggerOptions.parameter;
  41448. }
  41449. else {
  41450. this.trigger = triggerOptions;
  41451. }
  41452. this._nextActiveAction = this;
  41453. this._condition = condition;
  41454. }
  41455. // Methods
  41456. Action.prototype._prepare = function () {
  41457. };
  41458. Action.prototype.getTriggerParameter = function () {
  41459. return this._triggerParameter;
  41460. };
  41461. Action.prototype._executeCurrent = function (evt) {
  41462. if (this._nextActiveAction._condition) {
  41463. var condition = this._nextActiveAction._condition;
  41464. var currentRenderId = this._actionManager.getScene().getRenderId();
  41465. // We cache the current evaluation for the current frame
  41466. if (condition._evaluationId === currentRenderId) {
  41467. if (!condition._currentResult) {
  41468. return;
  41469. }
  41470. }
  41471. else {
  41472. condition._evaluationId = currentRenderId;
  41473. if (!condition.isValid()) {
  41474. condition._currentResult = false;
  41475. return;
  41476. }
  41477. condition._currentResult = true;
  41478. }
  41479. }
  41480. this.onBeforeExecuteObservable.notifyObservers(this);
  41481. this._nextActiveAction.execute(evt);
  41482. this.skipToNextActiveAction();
  41483. };
  41484. Action.prototype.execute = function (evt) {
  41485. };
  41486. Action.prototype.skipToNextActiveAction = function () {
  41487. if (this._nextActiveAction._child) {
  41488. if (!this._nextActiveAction._child._actionManager) {
  41489. this._nextActiveAction._child._actionManager = this._actionManager;
  41490. }
  41491. this._nextActiveAction = this._nextActiveAction._child;
  41492. }
  41493. else {
  41494. this._nextActiveAction = this;
  41495. }
  41496. };
  41497. Action.prototype.then = function (action) {
  41498. this._child = action;
  41499. action._actionManager = this._actionManager;
  41500. action._prepare();
  41501. return action;
  41502. };
  41503. Action.prototype._getProperty = function (propertyPath) {
  41504. return this._actionManager._getProperty(propertyPath);
  41505. };
  41506. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41507. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41508. };
  41509. Action.prototype.serialize = function (parent) {
  41510. };
  41511. // Called by BABYLON.Action objects in serialize(...). Internal use
  41512. Action.prototype._serialize = function (serializedAction, parent) {
  41513. var serializationObject = {
  41514. type: 1,
  41515. children: [],
  41516. name: serializedAction.name,
  41517. properties: serializedAction.properties || []
  41518. };
  41519. // Serialize child
  41520. if (this._child) {
  41521. this._child.serialize(serializationObject);
  41522. }
  41523. // Check if "this" has a condition
  41524. if (this._condition) {
  41525. var serializedCondition = this._condition.serialize();
  41526. serializedCondition.children.push(serializationObject);
  41527. if (parent) {
  41528. parent.children.push(serializedCondition);
  41529. }
  41530. return serializedCondition;
  41531. }
  41532. if (parent) {
  41533. parent.children.push(serializationObject);
  41534. }
  41535. return serializationObject;
  41536. };
  41537. Action._SerializeValueAsString = function (value) {
  41538. if (typeof value === "number") {
  41539. return value.toString();
  41540. }
  41541. if (typeof value === "boolean") {
  41542. return value ? "true" : "false";
  41543. }
  41544. if (value instanceof BABYLON.Vector2) {
  41545. return value.x + ", " + value.y;
  41546. }
  41547. if (value instanceof BABYLON.Vector3) {
  41548. return value.x + ", " + value.y + ", " + value.z;
  41549. }
  41550. if (value instanceof BABYLON.Color3) {
  41551. return value.r + ", " + value.g + ", " + value.b;
  41552. }
  41553. if (value instanceof BABYLON.Color4) {
  41554. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41555. }
  41556. return value; // string
  41557. };
  41558. Action._GetTargetProperty = function (target) {
  41559. return {
  41560. name: "target",
  41561. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41562. : target instanceof BABYLON.Light ? "LightProperties"
  41563. : target instanceof BABYLON.Camera ? "CameraProperties"
  41564. : "SceneProperties",
  41565. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41566. };
  41567. };
  41568. return Action;
  41569. }());
  41570. BABYLON.Action = Action;
  41571. })(BABYLON || (BABYLON = {}));
  41572. //# sourceMappingURL=babylon.action.js.map
  41573. var BABYLON;
  41574. (function (BABYLON) {
  41575. /**
  41576. * ActionEvent is the event beint sent when an action is triggered.
  41577. */
  41578. var ActionEvent = /** @class */ (function () {
  41579. /**
  41580. * @param source The mesh or sprite that triggered the action.
  41581. * @param pointerX The X mouse cursor position at the time of the event
  41582. * @param pointerY The Y mouse cursor position at the time of the event
  41583. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41584. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41585. */
  41586. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41587. this.source = source;
  41588. this.pointerX = pointerX;
  41589. this.pointerY = pointerY;
  41590. this.meshUnderPointer = meshUnderPointer;
  41591. this.sourceEvent = sourceEvent;
  41592. this.additionalData = additionalData;
  41593. }
  41594. /**
  41595. * Helper function to auto-create an ActionEvent from a source mesh.
  41596. * @param source The source mesh that triggered the event
  41597. * @param evt {Event} The original (browser) event
  41598. */
  41599. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41600. var scene = source.getScene();
  41601. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41602. };
  41603. /**
  41604. * Helper function to auto-create an ActionEvent from a source mesh.
  41605. * @param source The source sprite that triggered the event
  41606. * @param scene Scene associated with the sprite
  41607. * @param evt {Event} The original (browser) event
  41608. */
  41609. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41610. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41611. };
  41612. /**
  41613. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41614. * @param scene the scene where the event occurred
  41615. * @param evt {Event} The original (browser) event
  41616. */
  41617. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41618. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41619. };
  41620. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41621. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41622. };
  41623. return ActionEvent;
  41624. }());
  41625. BABYLON.ActionEvent = ActionEvent;
  41626. /**
  41627. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41628. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41629. */
  41630. var ActionManager = /** @class */ (function () {
  41631. function ActionManager(scene) {
  41632. // Members
  41633. this.actions = new Array();
  41634. this.hoverCursor = '';
  41635. this._scene = scene;
  41636. scene._actionManagers.push(this);
  41637. }
  41638. Object.defineProperty(ActionManager, "NothingTrigger", {
  41639. get: function () {
  41640. return ActionManager._NothingTrigger;
  41641. },
  41642. enumerable: true,
  41643. configurable: true
  41644. });
  41645. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41646. get: function () {
  41647. return ActionManager._OnPickTrigger;
  41648. },
  41649. enumerable: true,
  41650. configurable: true
  41651. });
  41652. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41653. get: function () {
  41654. return ActionManager._OnLeftPickTrigger;
  41655. },
  41656. enumerable: true,
  41657. configurable: true
  41658. });
  41659. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41660. get: function () {
  41661. return ActionManager._OnRightPickTrigger;
  41662. },
  41663. enumerable: true,
  41664. configurable: true
  41665. });
  41666. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41667. get: function () {
  41668. return ActionManager._OnCenterPickTrigger;
  41669. },
  41670. enumerable: true,
  41671. configurable: true
  41672. });
  41673. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41674. get: function () {
  41675. return ActionManager._OnPickDownTrigger;
  41676. },
  41677. enumerable: true,
  41678. configurable: true
  41679. });
  41680. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41681. get: function () {
  41682. return ActionManager._OnDoublePickTrigger;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41688. get: function () {
  41689. return ActionManager._OnPickUpTrigger;
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41695. /// This trigger will only be raised if you also declared a OnPickDown
  41696. get: function () {
  41697. return ActionManager._OnPickOutTrigger;
  41698. },
  41699. enumerable: true,
  41700. configurable: true
  41701. });
  41702. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41703. get: function () {
  41704. return ActionManager._OnLongPressTrigger;
  41705. },
  41706. enumerable: true,
  41707. configurable: true
  41708. });
  41709. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41710. get: function () {
  41711. return ActionManager._OnPointerOverTrigger;
  41712. },
  41713. enumerable: true,
  41714. configurable: true
  41715. });
  41716. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41717. get: function () {
  41718. return ActionManager._OnPointerOutTrigger;
  41719. },
  41720. enumerable: true,
  41721. configurable: true
  41722. });
  41723. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41724. get: function () {
  41725. return ActionManager._OnEveryFrameTrigger;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41731. get: function () {
  41732. return ActionManager._OnIntersectionEnterTrigger;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41738. get: function () {
  41739. return ActionManager._OnIntersectionExitTrigger;
  41740. },
  41741. enumerable: true,
  41742. configurable: true
  41743. });
  41744. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41745. get: function () {
  41746. return ActionManager._OnKeyDownTrigger;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41752. get: function () {
  41753. return ActionManager._OnKeyUpTrigger;
  41754. },
  41755. enumerable: true,
  41756. configurable: true
  41757. });
  41758. // Methods
  41759. ActionManager.prototype.dispose = function () {
  41760. var index = this._scene._actionManagers.indexOf(this);
  41761. for (var i = 0; i < this.actions.length; i++) {
  41762. var action = this.actions[i];
  41763. ActionManager.Triggers[action.trigger]--;
  41764. if (ActionManager.Triggers[action.trigger] === 0) {
  41765. delete ActionManager.Triggers[action.trigger];
  41766. }
  41767. }
  41768. if (index > -1) {
  41769. this._scene._actionManagers.splice(index, 1);
  41770. }
  41771. };
  41772. ActionManager.prototype.getScene = function () {
  41773. return this._scene;
  41774. };
  41775. /**
  41776. * Does this action manager handles actions of any of the given triggers
  41777. * @param {number[]} triggers - the triggers to be tested
  41778. * @return {boolean} whether one (or more) of the triggers is handeled
  41779. */
  41780. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41781. for (var index = 0; index < this.actions.length; index++) {
  41782. var action = this.actions[index];
  41783. if (triggers.indexOf(action.trigger) > -1) {
  41784. return true;
  41785. }
  41786. }
  41787. return false;
  41788. };
  41789. /**
  41790. * Does this action manager handles actions of a given trigger
  41791. * @param {number} trigger - the trigger to be tested
  41792. * @return {boolean} whether the trigger is handeled
  41793. */
  41794. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41795. for (var index = 0; index < this.actions.length; index++) {
  41796. var action = this.actions[index];
  41797. if (action.trigger === trigger) {
  41798. return true;
  41799. }
  41800. }
  41801. return false;
  41802. };
  41803. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41804. /**
  41805. * Does this action manager has pointer triggers
  41806. * @return {boolean} whether or not it has pointer triggers
  41807. */
  41808. get: function () {
  41809. for (var index = 0; index < this.actions.length; index++) {
  41810. var action = this.actions[index];
  41811. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41812. return true;
  41813. }
  41814. }
  41815. return false;
  41816. },
  41817. enumerable: true,
  41818. configurable: true
  41819. });
  41820. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41821. /**
  41822. * Does this action manager has pick triggers
  41823. * @return {boolean} whether or not it has pick triggers
  41824. */
  41825. get: function () {
  41826. for (var index = 0; index < this.actions.length; index++) {
  41827. var action = this.actions[index];
  41828. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41829. return true;
  41830. }
  41831. }
  41832. return false;
  41833. },
  41834. enumerable: true,
  41835. configurable: true
  41836. });
  41837. Object.defineProperty(ActionManager, "HasTriggers", {
  41838. /**
  41839. * Does exist one action manager with at least one trigger
  41840. * @return {boolean} whether or not it exists one action manager with one trigger
  41841. **/
  41842. get: function () {
  41843. for (var t in ActionManager.Triggers) {
  41844. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41845. return true;
  41846. }
  41847. }
  41848. return false;
  41849. },
  41850. enumerable: true,
  41851. configurable: true
  41852. });
  41853. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41854. /**
  41855. * Does exist one action manager with at least one pick trigger
  41856. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41857. **/
  41858. get: function () {
  41859. for (var t in ActionManager.Triggers) {
  41860. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41861. var t_int = parseInt(t);
  41862. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41863. return true;
  41864. }
  41865. }
  41866. }
  41867. return false;
  41868. },
  41869. enumerable: true,
  41870. configurable: true
  41871. });
  41872. /**
  41873. * Does exist one action manager that handles actions of a given trigger
  41874. * @param {number} trigger - the trigger to be tested
  41875. * @return {boolean} whether the trigger is handeled by at least one action manager
  41876. **/
  41877. ActionManager.HasSpecificTrigger = function (trigger) {
  41878. for (var t in ActionManager.Triggers) {
  41879. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41880. var t_int = parseInt(t);
  41881. if (t_int === trigger) {
  41882. return true;
  41883. }
  41884. }
  41885. }
  41886. return false;
  41887. };
  41888. /**
  41889. * Registers an action to this action manager
  41890. * @param {BABYLON.Action} action - the action to be registered
  41891. * @return {BABYLON.Action} the action amended (prepared) after registration
  41892. */
  41893. ActionManager.prototype.registerAction = function (action) {
  41894. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41895. if (this.getScene().actionManager !== this) {
  41896. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41897. return null;
  41898. }
  41899. }
  41900. this.actions.push(action);
  41901. if (ActionManager.Triggers[action.trigger]) {
  41902. ActionManager.Triggers[action.trigger]++;
  41903. }
  41904. else {
  41905. ActionManager.Triggers[action.trigger] = 1;
  41906. }
  41907. action._actionManager = this;
  41908. action._prepare();
  41909. return action;
  41910. };
  41911. /**
  41912. * Process a specific trigger
  41913. * @param {number} trigger - the trigger to process
  41914. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41915. */
  41916. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41917. for (var index = 0; index < this.actions.length; index++) {
  41918. var action = this.actions[index];
  41919. if (action.trigger === trigger) {
  41920. if (evt) {
  41921. if (trigger === ActionManager.OnKeyUpTrigger
  41922. || trigger === ActionManager.OnKeyDownTrigger) {
  41923. var parameter = action.getTriggerParameter();
  41924. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41925. if (!parameter.toLowerCase) {
  41926. continue;
  41927. }
  41928. var lowerCase = parameter.toLowerCase();
  41929. if (lowerCase !== evt.sourceEvent.key) {
  41930. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41931. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41932. if (actualkey !== lowerCase) {
  41933. continue;
  41934. }
  41935. }
  41936. }
  41937. }
  41938. }
  41939. action._executeCurrent(evt);
  41940. }
  41941. }
  41942. };
  41943. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41944. var properties = propertyPath.split(".");
  41945. for (var index = 0; index < properties.length - 1; index++) {
  41946. target = target[properties[index]];
  41947. }
  41948. return target;
  41949. };
  41950. ActionManager.prototype._getProperty = function (propertyPath) {
  41951. var properties = propertyPath.split(".");
  41952. return properties[properties.length - 1];
  41953. };
  41954. ActionManager.prototype.serialize = function (name) {
  41955. var root = {
  41956. children: new Array(),
  41957. name: name,
  41958. type: 3,
  41959. properties: new Array() // Empty for root but required
  41960. };
  41961. for (var i = 0; i < this.actions.length; i++) {
  41962. var triggerObject = {
  41963. type: 0,
  41964. children: new Array(),
  41965. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41966. properties: new Array()
  41967. };
  41968. var triggerOptions = this.actions[i].triggerOptions;
  41969. if (triggerOptions && typeof triggerOptions !== "number") {
  41970. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41971. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41972. }
  41973. else {
  41974. var parameter = {};
  41975. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41976. if (triggerOptions.parameter.mesh) {
  41977. parameter._meshId = triggerOptions.parameter.mesh.id;
  41978. }
  41979. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41980. }
  41981. }
  41982. // Serialize child action, recursively
  41983. this.actions[i].serialize(triggerObject);
  41984. // Add serialized trigger
  41985. root.children.push(triggerObject);
  41986. }
  41987. return root;
  41988. };
  41989. ActionManager.Parse = function (parsedActions, object, scene) {
  41990. var actionManager = new BABYLON.ActionManager(scene);
  41991. if (object === null)
  41992. scene.actionManager = actionManager;
  41993. else
  41994. object.actionManager = actionManager;
  41995. // instanciate a new object
  41996. var instanciate = function (name, params) {
  41997. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41998. newInstance.constructor.apply(newInstance, params);
  41999. return newInstance;
  42000. };
  42001. var parseParameter = function (name, value, target, propertyPath) {
  42002. if (propertyPath === null) {
  42003. // String, boolean or float
  42004. var floatValue = parseFloat(value);
  42005. if (value === "true" || value === "false")
  42006. return value === "true";
  42007. else
  42008. return isNaN(floatValue) ? value : floatValue;
  42009. }
  42010. var effectiveTarget = propertyPath.split(".");
  42011. var values = value.split(",");
  42012. // Get effective Target
  42013. for (var i = 0; i < effectiveTarget.length; i++) {
  42014. target = target[effectiveTarget[i]];
  42015. }
  42016. // Return appropriate value with its type
  42017. if (typeof (target) === "boolean")
  42018. return values[0] === "true";
  42019. if (typeof (target) === "string")
  42020. return values[0];
  42021. // Parameters with multiple values such as Vector3 etc.
  42022. var split = new Array();
  42023. for (var i = 0; i < values.length; i++)
  42024. split.push(parseFloat(values[i]));
  42025. if (target instanceof BABYLON.Vector3)
  42026. return BABYLON.Vector3.FromArray(split);
  42027. if (target instanceof BABYLON.Vector4)
  42028. return BABYLON.Vector4.FromArray(split);
  42029. if (target instanceof BABYLON.Color3)
  42030. return BABYLON.Color3.FromArray(split);
  42031. if (target instanceof BABYLON.Color4)
  42032. return BABYLON.Color4.FromArray(split);
  42033. return parseFloat(values[0]);
  42034. };
  42035. // traverse graph per trigger
  42036. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42037. if (combineArray === void 0) { combineArray = null; }
  42038. if (parsedAction.detached)
  42039. return;
  42040. var parameters = new Array();
  42041. var target = null;
  42042. var propertyPath = null;
  42043. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42044. // Parameters
  42045. if (parsedAction.type === 2)
  42046. parameters.push(actionManager);
  42047. else
  42048. parameters.push(trigger);
  42049. if (combine) {
  42050. var actions = new Array();
  42051. for (var j = 0; j < parsedAction.combine.length; j++) {
  42052. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42053. }
  42054. parameters.push(actions);
  42055. }
  42056. else {
  42057. for (var i = 0; i < parsedAction.properties.length; i++) {
  42058. var value = parsedAction.properties[i].value;
  42059. var name = parsedAction.properties[i].name;
  42060. var targetType = parsedAction.properties[i].targetType;
  42061. if (name === "target")
  42062. if (targetType !== null && targetType === "SceneProperties")
  42063. value = target = scene;
  42064. else
  42065. value = target = scene.getNodeByName(value);
  42066. else if (name === "parent")
  42067. value = scene.getNodeByName(value);
  42068. else if (name === "sound")
  42069. value = scene.getSoundByName(value);
  42070. else if (name !== "propertyPath") {
  42071. if (parsedAction.type === 2 && name === "operator")
  42072. value = BABYLON.ValueCondition[value];
  42073. else
  42074. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42075. }
  42076. else {
  42077. propertyPath = value;
  42078. }
  42079. parameters.push(value);
  42080. }
  42081. }
  42082. if (combineArray === null) {
  42083. parameters.push(condition);
  42084. }
  42085. else {
  42086. parameters.push(null);
  42087. }
  42088. // If interpolate value action
  42089. if (parsedAction.name === "InterpolateValueAction") {
  42090. var param = parameters[parameters.length - 2];
  42091. parameters[parameters.length - 1] = param;
  42092. parameters[parameters.length - 2] = condition;
  42093. }
  42094. // Action or condition(s) and not CombineAction
  42095. var newAction = instanciate(parsedAction.name, parameters);
  42096. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42097. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42098. if (action)
  42099. action.then(nothing);
  42100. else
  42101. actionManager.registerAction(nothing);
  42102. action = nothing;
  42103. }
  42104. if (combineArray === null) {
  42105. if (newAction instanceof BABYLON.Condition) {
  42106. condition = newAction;
  42107. newAction = action;
  42108. }
  42109. else {
  42110. condition = null;
  42111. if (action)
  42112. action.then(newAction);
  42113. else
  42114. actionManager.registerAction(newAction);
  42115. }
  42116. }
  42117. else {
  42118. combineArray.push(newAction);
  42119. }
  42120. for (var i = 0; i < parsedAction.children.length; i++)
  42121. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42122. };
  42123. // triggers
  42124. for (var i = 0; i < parsedActions.children.length; i++) {
  42125. var triggerParams;
  42126. var trigger = parsedActions.children[i];
  42127. if (trigger.properties.length > 0) {
  42128. var param = trigger.properties[0].value;
  42129. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42130. if (value._meshId) {
  42131. value.mesh = scene.getMeshByID(value._meshId);
  42132. }
  42133. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42134. }
  42135. else
  42136. triggerParams = ActionManager[trigger.name];
  42137. for (var j = 0; j < trigger.children.length; j++) {
  42138. if (!trigger.detached)
  42139. traverse(trigger.children[j], triggerParams, null, null);
  42140. }
  42141. }
  42142. };
  42143. ActionManager.GetTriggerName = function (trigger) {
  42144. switch (trigger) {
  42145. case 0: return "NothingTrigger";
  42146. case 1: return "OnPickTrigger";
  42147. case 2: return "OnLeftPickTrigger";
  42148. case 3: return "OnRightPickTrigger";
  42149. case 4: return "OnCenterPickTrigger";
  42150. case 5: return "OnPickDownTrigger";
  42151. case 6: return "OnPickUpTrigger";
  42152. case 7: return "OnLongPressTrigger";
  42153. case 8: return "OnPointerOverTrigger";
  42154. case 9: return "OnPointerOutTrigger";
  42155. case 10: return "OnEveryFrameTrigger";
  42156. case 11: return "OnIntersectionEnterTrigger";
  42157. case 12: return "OnIntersectionExitTrigger";
  42158. case 13: return "OnKeyDownTrigger";
  42159. case 14: return "OnKeyUpTrigger";
  42160. case 15: return "OnPickOutTrigger";
  42161. default: return "";
  42162. }
  42163. };
  42164. // Statics
  42165. ActionManager._NothingTrigger = 0;
  42166. ActionManager._OnPickTrigger = 1;
  42167. ActionManager._OnLeftPickTrigger = 2;
  42168. ActionManager._OnRightPickTrigger = 3;
  42169. ActionManager._OnCenterPickTrigger = 4;
  42170. ActionManager._OnPickDownTrigger = 5;
  42171. ActionManager._OnDoublePickTrigger = 6;
  42172. ActionManager._OnPickUpTrigger = 7;
  42173. ActionManager._OnLongPressTrigger = 8;
  42174. ActionManager._OnPointerOverTrigger = 9;
  42175. ActionManager._OnPointerOutTrigger = 10;
  42176. ActionManager._OnEveryFrameTrigger = 11;
  42177. ActionManager._OnIntersectionEnterTrigger = 12;
  42178. ActionManager._OnIntersectionExitTrigger = 13;
  42179. ActionManager._OnKeyDownTrigger = 14;
  42180. ActionManager._OnKeyUpTrigger = 15;
  42181. ActionManager._OnPickOutTrigger = 16;
  42182. ActionManager.Triggers = {};
  42183. return ActionManager;
  42184. }());
  42185. BABYLON.ActionManager = ActionManager;
  42186. })(BABYLON || (BABYLON = {}));
  42187. //# sourceMappingURL=babylon.actionManager.js.map
  42188. var BABYLON;
  42189. (function (BABYLON) {
  42190. var InterpolateValueAction = /** @class */ (function (_super) {
  42191. __extends(InterpolateValueAction, _super);
  42192. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42193. if (duration === void 0) { duration = 1000; }
  42194. var _this = _super.call(this, triggerOptions, condition) || this;
  42195. _this.propertyPath = propertyPath;
  42196. _this.value = value;
  42197. _this.duration = duration;
  42198. _this.stopOtherAnimations = stopOtherAnimations;
  42199. _this.onInterpolationDone = onInterpolationDone;
  42200. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42201. _this._target = _this._effectiveTarget = target;
  42202. return _this;
  42203. }
  42204. InterpolateValueAction.prototype._prepare = function () {
  42205. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42206. this._property = this._getProperty(this.propertyPath);
  42207. };
  42208. InterpolateValueAction.prototype.execute = function () {
  42209. var _this = this;
  42210. var scene = this._actionManager.getScene();
  42211. var keys = [
  42212. {
  42213. frame: 0,
  42214. value: this._effectiveTarget[this._property]
  42215. }, {
  42216. frame: 100,
  42217. value: this.value
  42218. }
  42219. ];
  42220. var dataType;
  42221. if (typeof this.value === "number") {
  42222. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42223. }
  42224. else if (this.value instanceof BABYLON.Color3) {
  42225. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42226. }
  42227. else if (this.value instanceof BABYLON.Vector3) {
  42228. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42229. }
  42230. else if (this.value instanceof BABYLON.Matrix) {
  42231. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42232. }
  42233. else if (this.value instanceof BABYLON.Quaternion) {
  42234. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42235. }
  42236. else {
  42237. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42238. return;
  42239. }
  42240. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42241. animation.setKeys(keys);
  42242. if (this.stopOtherAnimations) {
  42243. scene.stopAnimation(this._effectiveTarget);
  42244. }
  42245. var wrapper = function () {
  42246. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42247. if (_this.onInterpolationDone) {
  42248. _this.onInterpolationDone();
  42249. }
  42250. };
  42251. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42252. };
  42253. InterpolateValueAction.prototype.serialize = function (parent) {
  42254. return _super.prototype._serialize.call(this, {
  42255. name: "InterpolateValueAction",
  42256. properties: [
  42257. BABYLON.Action._GetTargetProperty(this._target),
  42258. { name: "propertyPath", value: this.propertyPath },
  42259. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42260. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42261. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42262. ]
  42263. }, parent);
  42264. };
  42265. return InterpolateValueAction;
  42266. }(BABYLON.Action));
  42267. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42268. })(BABYLON || (BABYLON = {}));
  42269. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42270. var BABYLON;
  42271. (function (BABYLON) {
  42272. var SwitchBooleanAction = /** @class */ (function (_super) {
  42273. __extends(SwitchBooleanAction, _super);
  42274. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42275. var _this = _super.call(this, triggerOptions, condition) || this;
  42276. _this.propertyPath = propertyPath;
  42277. _this._target = _this._effectiveTarget = target;
  42278. return _this;
  42279. }
  42280. SwitchBooleanAction.prototype._prepare = function () {
  42281. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42282. this._property = this._getProperty(this.propertyPath);
  42283. };
  42284. SwitchBooleanAction.prototype.execute = function () {
  42285. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42286. };
  42287. SwitchBooleanAction.prototype.serialize = function (parent) {
  42288. return _super.prototype._serialize.call(this, {
  42289. name: "SwitchBooleanAction",
  42290. properties: [
  42291. BABYLON.Action._GetTargetProperty(this._target),
  42292. { name: "propertyPath", value: this.propertyPath }
  42293. ]
  42294. }, parent);
  42295. };
  42296. return SwitchBooleanAction;
  42297. }(BABYLON.Action));
  42298. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42299. var SetStateAction = /** @class */ (function (_super) {
  42300. __extends(SetStateAction, _super);
  42301. function SetStateAction(triggerOptions, target, value, condition) {
  42302. var _this = _super.call(this, triggerOptions, condition) || this;
  42303. _this.value = value;
  42304. _this._target = target;
  42305. return _this;
  42306. }
  42307. SetStateAction.prototype.execute = function () {
  42308. this._target.state = this.value;
  42309. };
  42310. SetStateAction.prototype.serialize = function (parent) {
  42311. return _super.prototype._serialize.call(this, {
  42312. name: "SetStateAction",
  42313. properties: [
  42314. BABYLON.Action._GetTargetProperty(this._target),
  42315. { name: "value", value: this.value }
  42316. ]
  42317. }, parent);
  42318. };
  42319. return SetStateAction;
  42320. }(BABYLON.Action));
  42321. BABYLON.SetStateAction = SetStateAction;
  42322. var SetValueAction = /** @class */ (function (_super) {
  42323. __extends(SetValueAction, _super);
  42324. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42325. var _this = _super.call(this, triggerOptions, condition) || this;
  42326. _this.propertyPath = propertyPath;
  42327. _this.value = value;
  42328. _this._target = _this._effectiveTarget = target;
  42329. return _this;
  42330. }
  42331. SetValueAction.prototype._prepare = function () {
  42332. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42333. this._property = this._getProperty(this.propertyPath);
  42334. };
  42335. SetValueAction.prototype.execute = function () {
  42336. this._effectiveTarget[this._property] = this.value;
  42337. if (this._target.markAsDirty) {
  42338. this._target.markAsDirty(this._property);
  42339. }
  42340. };
  42341. SetValueAction.prototype.serialize = function (parent) {
  42342. return _super.prototype._serialize.call(this, {
  42343. name: "SetValueAction",
  42344. properties: [
  42345. BABYLON.Action._GetTargetProperty(this._target),
  42346. { name: "propertyPath", value: this.propertyPath },
  42347. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42348. ]
  42349. }, parent);
  42350. };
  42351. return SetValueAction;
  42352. }(BABYLON.Action));
  42353. BABYLON.SetValueAction = SetValueAction;
  42354. var IncrementValueAction = /** @class */ (function (_super) {
  42355. __extends(IncrementValueAction, _super);
  42356. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42357. var _this = _super.call(this, triggerOptions, condition) || this;
  42358. _this.propertyPath = propertyPath;
  42359. _this.value = value;
  42360. _this._target = _this._effectiveTarget = target;
  42361. return _this;
  42362. }
  42363. IncrementValueAction.prototype._prepare = function () {
  42364. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42365. this._property = this._getProperty(this.propertyPath);
  42366. if (typeof this._effectiveTarget[this._property] !== "number") {
  42367. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42368. }
  42369. };
  42370. IncrementValueAction.prototype.execute = function () {
  42371. this._effectiveTarget[this._property] += this.value;
  42372. if (this._target.markAsDirty) {
  42373. this._target.markAsDirty(this._property);
  42374. }
  42375. };
  42376. IncrementValueAction.prototype.serialize = function (parent) {
  42377. return _super.prototype._serialize.call(this, {
  42378. name: "IncrementValueAction",
  42379. properties: [
  42380. BABYLON.Action._GetTargetProperty(this._target),
  42381. { name: "propertyPath", value: this.propertyPath },
  42382. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42383. ]
  42384. }, parent);
  42385. };
  42386. return IncrementValueAction;
  42387. }(BABYLON.Action));
  42388. BABYLON.IncrementValueAction = IncrementValueAction;
  42389. var PlayAnimationAction = /** @class */ (function (_super) {
  42390. __extends(PlayAnimationAction, _super);
  42391. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42392. var _this = _super.call(this, triggerOptions, condition) || this;
  42393. _this.from = from;
  42394. _this.to = to;
  42395. _this.loop = loop;
  42396. _this._target = target;
  42397. return _this;
  42398. }
  42399. PlayAnimationAction.prototype._prepare = function () {
  42400. };
  42401. PlayAnimationAction.prototype.execute = function () {
  42402. var scene = this._actionManager.getScene();
  42403. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42404. };
  42405. PlayAnimationAction.prototype.serialize = function (parent) {
  42406. return _super.prototype._serialize.call(this, {
  42407. name: "PlayAnimationAction",
  42408. properties: [
  42409. BABYLON.Action._GetTargetProperty(this._target),
  42410. { name: "from", value: String(this.from) },
  42411. { name: "to", value: String(this.to) },
  42412. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42413. ]
  42414. }, parent);
  42415. };
  42416. return PlayAnimationAction;
  42417. }(BABYLON.Action));
  42418. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42419. var StopAnimationAction = /** @class */ (function (_super) {
  42420. __extends(StopAnimationAction, _super);
  42421. function StopAnimationAction(triggerOptions, target, condition) {
  42422. var _this = _super.call(this, triggerOptions, condition) || this;
  42423. _this._target = target;
  42424. return _this;
  42425. }
  42426. StopAnimationAction.prototype._prepare = function () {
  42427. };
  42428. StopAnimationAction.prototype.execute = function () {
  42429. var scene = this._actionManager.getScene();
  42430. scene.stopAnimation(this._target);
  42431. };
  42432. StopAnimationAction.prototype.serialize = function (parent) {
  42433. return _super.prototype._serialize.call(this, {
  42434. name: "StopAnimationAction",
  42435. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42436. }, parent);
  42437. };
  42438. return StopAnimationAction;
  42439. }(BABYLON.Action));
  42440. BABYLON.StopAnimationAction = StopAnimationAction;
  42441. var DoNothingAction = /** @class */ (function (_super) {
  42442. __extends(DoNothingAction, _super);
  42443. function DoNothingAction(triggerOptions, condition) {
  42444. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42445. return _super.call(this, triggerOptions, condition) || this;
  42446. }
  42447. DoNothingAction.prototype.execute = function () {
  42448. };
  42449. DoNothingAction.prototype.serialize = function (parent) {
  42450. return _super.prototype._serialize.call(this, {
  42451. name: "DoNothingAction",
  42452. properties: []
  42453. }, parent);
  42454. };
  42455. return DoNothingAction;
  42456. }(BABYLON.Action));
  42457. BABYLON.DoNothingAction = DoNothingAction;
  42458. var CombineAction = /** @class */ (function (_super) {
  42459. __extends(CombineAction, _super);
  42460. function CombineAction(triggerOptions, children, condition) {
  42461. var _this = _super.call(this, triggerOptions, condition) || this;
  42462. _this.children = children;
  42463. return _this;
  42464. }
  42465. CombineAction.prototype._prepare = function () {
  42466. for (var index = 0; index < this.children.length; index++) {
  42467. this.children[index]._actionManager = this._actionManager;
  42468. this.children[index]._prepare();
  42469. }
  42470. };
  42471. CombineAction.prototype.execute = function (evt) {
  42472. for (var index = 0; index < this.children.length; index++) {
  42473. this.children[index].execute(evt);
  42474. }
  42475. };
  42476. CombineAction.prototype.serialize = function (parent) {
  42477. var serializationObject = _super.prototype._serialize.call(this, {
  42478. name: "CombineAction",
  42479. properties: [],
  42480. combine: []
  42481. }, parent);
  42482. for (var i = 0; i < this.children.length; i++) {
  42483. serializationObject.combine.push(this.children[i].serialize(null));
  42484. }
  42485. return serializationObject;
  42486. };
  42487. return CombineAction;
  42488. }(BABYLON.Action));
  42489. BABYLON.CombineAction = CombineAction;
  42490. var ExecuteCodeAction = /** @class */ (function (_super) {
  42491. __extends(ExecuteCodeAction, _super);
  42492. function ExecuteCodeAction(triggerOptions, func, condition) {
  42493. var _this = _super.call(this, triggerOptions, condition) || this;
  42494. _this.func = func;
  42495. return _this;
  42496. }
  42497. ExecuteCodeAction.prototype.execute = function (evt) {
  42498. this.func(evt);
  42499. };
  42500. return ExecuteCodeAction;
  42501. }(BABYLON.Action));
  42502. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42503. var SetParentAction = /** @class */ (function (_super) {
  42504. __extends(SetParentAction, _super);
  42505. function SetParentAction(triggerOptions, target, parent, condition) {
  42506. var _this = _super.call(this, triggerOptions, condition) || this;
  42507. _this._target = target;
  42508. _this._parent = parent;
  42509. return _this;
  42510. }
  42511. SetParentAction.prototype._prepare = function () {
  42512. };
  42513. SetParentAction.prototype.execute = function () {
  42514. if (this._target.parent === this._parent) {
  42515. return;
  42516. }
  42517. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42518. invertParentWorldMatrix.invert();
  42519. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42520. this._target.parent = this._parent;
  42521. };
  42522. SetParentAction.prototype.serialize = function (parent) {
  42523. return _super.prototype._serialize.call(this, {
  42524. name: "SetParentAction",
  42525. properties: [
  42526. BABYLON.Action._GetTargetProperty(this._target),
  42527. BABYLON.Action._GetTargetProperty(this._parent),
  42528. ]
  42529. }, parent);
  42530. };
  42531. return SetParentAction;
  42532. }(BABYLON.Action));
  42533. BABYLON.SetParentAction = SetParentAction;
  42534. var PlaySoundAction = /** @class */ (function (_super) {
  42535. __extends(PlaySoundAction, _super);
  42536. function PlaySoundAction(triggerOptions, sound, condition) {
  42537. var _this = _super.call(this, triggerOptions, condition) || this;
  42538. _this._sound = sound;
  42539. return _this;
  42540. }
  42541. PlaySoundAction.prototype._prepare = function () {
  42542. };
  42543. PlaySoundAction.prototype.execute = function () {
  42544. if (this._sound !== undefined)
  42545. this._sound.play();
  42546. };
  42547. PlaySoundAction.prototype.serialize = function (parent) {
  42548. return _super.prototype._serialize.call(this, {
  42549. name: "PlaySoundAction",
  42550. properties: [{ name: "sound", value: this._sound.name }]
  42551. }, parent);
  42552. };
  42553. return PlaySoundAction;
  42554. }(BABYLON.Action));
  42555. BABYLON.PlaySoundAction = PlaySoundAction;
  42556. var StopSoundAction = /** @class */ (function (_super) {
  42557. __extends(StopSoundAction, _super);
  42558. function StopSoundAction(triggerOptions, sound, condition) {
  42559. var _this = _super.call(this, triggerOptions, condition) || this;
  42560. _this._sound = sound;
  42561. return _this;
  42562. }
  42563. StopSoundAction.prototype._prepare = function () {
  42564. };
  42565. StopSoundAction.prototype.execute = function () {
  42566. if (this._sound !== undefined)
  42567. this._sound.stop();
  42568. };
  42569. StopSoundAction.prototype.serialize = function (parent) {
  42570. return _super.prototype._serialize.call(this, {
  42571. name: "StopSoundAction",
  42572. properties: [{ name: "sound", value: this._sound.name }]
  42573. }, parent);
  42574. };
  42575. return StopSoundAction;
  42576. }(BABYLON.Action));
  42577. BABYLON.StopSoundAction = StopSoundAction;
  42578. })(BABYLON || (BABYLON = {}));
  42579. //# sourceMappingURL=babylon.directActions.js.map
  42580. var BABYLON;
  42581. (function (BABYLON) {
  42582. var SpriteManager = /** @class */ (function () {
  42583. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42584. if (epsilon === void 0) { epsilon = 0.01; }
  42585. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42586. this.name = name;
  42587. this.sprites = new Array();
  42588. this.renderingGroupId = 0;
  42589. this.layerMask = 0x0FFFFFFF;
  42590. this.fogEnabled = true;
  42591. this.isPickable = false;
  42592. /**
  42593. * An event triggered when the manager is disposed.
  42594. * @type {BABYLON.Observable}
  42595. */
  42596. this.onDisposeObservable = new BABYLON.Observable();
  42597. this._vertexBuffers = {};
  42598. this._capacity = capacity;
  42599. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42600. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42601. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42602. if (cellSize.width && cellSize.height) {
  42603. this.cellWidth = cellSize.width;
  42604. this.cellHeight = cellSize.height;
  42605. }
  42606. else if (cellSize !== undefined) {
  42607. this.cellWidth = cellSize;
  42608. this.cellHeight = cellSize;
  42609. }
  42610. else {
  42611. return;
  42612. }
  42613. this._epsilon = epsilon;
  42614. this._scene = scene;
  42615. this._scene.spriteManagers.push(this);
  42616. var indices = [];
  42617. var index = 0;
  42618. for (var count = 0; count < capacity; count++) {
  42619. indices.push(index);
  42620. indices.push(index + 1);
  42621. indices.push(index + 2);
  42622. indices.push(index);
  42623. indices.push(index + 2);
  42624. indices.push(index + 3);
  42625. index += 4;
  42626. }
  42627. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42628. // VBO
  42629. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42630. this._vertexData = new Float32Array(capacity * 16 * 4);
  42631. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42632. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42633. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42634. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42635. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42636. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42637. this._vertexBuffers["options"] = options;
  42638. this._vertexBuffers["cellInfo"] = cellInfo;
  42639. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42640. // Effects
  42641. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42642. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42643. }
  42644. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42645. set: function (callback) {
  42646. if (this._onDisposeObserver) {
  42647. this.onDisposeObservable.remove(this._onDisposeObserver);
  42648. }
  42649. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42650. },
  42651. enumerable: true,
  42652. configurable: true
  42653. });
  42654. Object.defineProperty(SpriteManager.prototype, "texture", {
  42655. get: function () {
  42656. return this._spriteTexture;
  42657. },
  42658. set: function (value) {
  42659. this._spriteTexture = value;
  42660. },
  42661. enumerable: true,
  42662. configurable: true
  42663. });
  42664. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42665. var arrayOffset = index * 16;
  42666. if (offsetX === 0)
  42667. offsetX = this._epsilon;
  42668. else if (offsetX === 1)
  42669. offsetX = 1 - this._epsilon;
  42670. if (offsetY === 0)
  42671. offsetY = this._epsilon;
  42672. else if (offsetY === 1)
  42673. offsetY = 1 - this._epsilon;
  42674. this._vertexData[arrayOffset] = sprite.position.x;
  42675. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42676. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42677. this._vertexData[arrayOffset + 3] = sprite.angle;
  42678. this._vertexData[arrayOffset + 4] = sprite.width;
  42679. this._vertexData[arrayOffset + 5] = sprite.height;
  42680. this._vertexData[arrayOffset + 6] = offsetX;
  42681. this._vertexData[arrayOffset + 7] = offsetY;
  42682. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42683. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42684. var offset = (sprite.cellIndex / rowSize) >> 0;
  42685. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42686. this._vertexData[arrayOffset + 11] = offset;
  42687. // Color
  42688. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42689. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42690. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42691. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42692. };
  42693. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42694. var count = Math.min(this._capacity, this.sprites.length);
  42695. var min = BABYLON.Vector3.Zero();
  42696. var max = BABYLON.Vector3.Zero();
  42697. var distance = Number.MAX_VALUE;
  42698. var currentSprite = null;
  42699. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42700. var cameraView = camera.getViewMatrix();
  42701. for (var index = 0; index < count; index++) {
  42702. var sprite = this.sprites[index];
  42703. if (!sprite) {
  42704. continue;
  42705. }
  42706. if (predicate) {
  42707. if (!predicate(sprite)) {
  42708. continue;
  42709. }
  42710. }
  42711. else if (!sprite.isPickable) {
  42712. continue;
  42713. }
  42714. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42715. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42716. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42717. if (ray.intersectsBoxMinMax(min, max)) {
  42718. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42719. if (distance > currentDistance) {
  42720. distance = currentDistance;
  42721. currentSprite = sprite;
  42722. if (fastCheck) {
  42723. break;
  42724. }
  42725. }
  42726. }
  42727. }
  42728. if (currentSprite) {
  42729. var result = new BABYLON.PickingInfo();
  42730. result.hit = true;
  42731. result.pickedSprite = currentSprite;
  42732. result.distance = distance;
  42733. return result;
  42734. }
  42735. return null;
  42736. };
  42737. SpriteManager.prototype.render = function () {
  42738. // Check
  42739. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42740. return;
  42741. var engine = this._scene.getEngine();
  42742. var baseSize = this._spriteTexture.getBaseSize();
  42743. // Sprites
  42744. var deltaTime = engine.getDeltaTime();
  42745. var max = Math.min(this._capacity, this.sprites.length);
  42746. var rowSize = baseSize.width / this.cellWidth;
  42747. var offset = 0;
  42748. for (var index = 0; index < max; index++) {
  42749. var sprite = this.sprites[index];
  42750. if (!sprite) {
  42751. continue;
  42752. }
  42753. sprite._animate(deltaTime);
  42754. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42755. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42756. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42757. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42758. }
  42759. this._buffer.update(this._vertexData);
  42760. // Render
  42761. var effect = this._effectBase;
  42762. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42763. effect = this._effectFog;
  42764. }
  42765. engine.enableEffect(effect);
  42766. var viewMatrix = this._scene.getViewMatrix();
  42767. effect.setTexture("diffuseSampler", this._spriteTexture);
  42768. effect.setMatrix("view", viewMatrix);
  42769. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42770. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42771. // Fog
  42772. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42773. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42774. effect.setColor3("vFogColor", this._scene.fogColor);
  42775. }
  42776. // VBOs
  42777. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42778. // Draw order
  42779. engine.setDepthFunctionToLessOrEqual();
  42780. effect.setBool("alphaTest", true);
  42781. engine.setColorWrite(false);
  42782. engine.draw(true, 0, max * 6);
  42783. engine.setColorWrite(true);
  42784. effect.setBool("alphaTest", false);
  42785. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42786. engine.draw(true, 0, max * 6);
  42787. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42788. };
  42789. SpriteManager.prototype.dispose = function () {
  42790. if (this._buffer) {
  42791. this._buffer.dispose();
  42792. this._buffer = null;
  42793. }
  42794. if (this._indexBuffer) {
  42795. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42796. this._indexBuffer = null;
  42797. }
  42798. if (this._spriteTexture) {
  42799. this._spriteTexture.dispose();
  42800. this._spriteTexture = null;
  42801. }
  42802. // Remove from scene
  42803. var index = this._scene.spriteManagers.indexOf(this);
  42804. this._scene.spriteManagers.splice(index, 1);
  42805. // Callback
  42806. this.onDisposeObservable.notifyObservers(this);
  42807. this.onDisposeObservable.clear();
  42808. };
  42809. return SpriteManager;
  42810. }());
  42811. BABYLON.SpriteManager = SpriteManager;
  42812. })(BABYLON || (BABYLON = {}));
  42813. //# sourceMappingURL=babylon.spriteManager.js.map
  42814. var BABYLON;
  42815. (function (BABYLON) {
  42816. var Sprite = /** @class */ (function () {
  42817. function Sprite(name, manager) {
  42818. this.name = name;
  42819. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42820. this.width = 1.0;
  42821. this.height = 1.0;
  42822. this.angle = 0;
  42823. this.cellIndex = 0;
  42824. this.invertU = 0;
  42825. this.invertV = 0;
  42826. this.animations = new Array();
  42827. this.isPickable = false;
  42828. this._animationStarted = false;
  42829. this._loopAnimation = false;
  42830. this._fromIndex = 0;
  42831. this._toIndex = 0;
  42832. this._delay = 0;
  42833. this._direction = 1;
  42834. this._time = 0;
  42835. this._manager = manager;
  42836. this._manager.sprites.push(this);
  42837. this.position = BABYLON.Vector3.Zero();
  42838. }
  42839. Object.defineProperty(Sprite.prototype, "size", {
  42840. get: function () {
  42841. return this.width;
  42842. },
  42843. set: function (value) {
  42844. this.width = value;
  42845. this.height = value;
  42846. },
  42847. enumerable: true,
  42848. configurable: true
  42849. });
  42850. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42851. this._fromIndex = from;
  42852. this._toIndex = to;
  42853. this._loopAnimation = loop;
  42854. this._delay = delay;
  42855. this._animationStarted = true;
  42856. this._direction = from < to ? 1 : -1;
  42857. this.cellIndex = from;
  42858. this._time = 0;
  42859. this._onAnimationEnd = onAnimationEnd;
  42860. };
  42861. Sprite.prototype.stopAnimation = function () {
  42862. this._animationStarted = false;
  42863. };
  42864. Sprite.prototype._animate = function (deltaTime) {
  42865. if (!this._animationStarted)
  42866. return;
  42867. this._time += deltaTime;
  42868. if (this._time > this._delay) {
  42869. this._time = this._time % this._delay;
  42870. this.cellIndex += this._direction;
  42871. if (this.cellIndex > this._toIndex) {
  42872. if (this._loopAnimation) {
  42873. this.cellIndex = this._fromIndex;
  42874. }
  42875. else {
  42876. this.cellIndex = this._toIndex;
  42877. this._animationStarted = false;
  42878. if (this._onAnimationEnd) {
  42879. this._onAnimationEnd();
  42880. }
  42881. if (this.disposeWhenFinishedAnimating) {
  42882. this.dispose();
  42883. }
  42884. }
  42885. }
  42886. }
  42887. };
  42888. Sprite.prototype.dispose = function () {
  42889. for (var i = 0; i < this._manager.sprites.length; i++) {
  42890. if (this._manager.sprites[i] == this) {
  42891. this._manager.sprites.splice(i, 1);
  42892. }
  42893. }
  42894. };
  42895. return Sprite;
  42896. }());
  42897. BABYLON.Sprite = Sprite;
  42898. })(BABYLON || (BABYLON = {}));
  42899. //# sourceMappingURL=babylon.sprite.js.map
  42900. var BABYLON;
  42901. (function (BABYLON) {
  42902. var IntersectionInfo = /** @class */ (function () {
  42903. function IntersectionInfo(bu, bv, distance) {
  42904. this.bu = bu;
  42905. this.bv = bv;
  42906. this.distance = distance;
  42907. this.faceId = 0;
  42908. this.subMeshId = 0;
  42909. }
  42910. return IntersectionInfo;
  42911. }());
  42912. BABYLON.IntersectionInfo = IntersectionInfo;
  42913. var PickingInfo = /** @class */ (function () {
  42914. function PickingInfo() {
  42915. this.hit = false;
  42916. this.distance = 0;
  42917. this.pickedPoint = null;
  42918. this.pickedMesh = null;
  42919. this.bu = 0;
  42920. this.bv = 0;
  42921. this.faceId = -1;
  42922. this.subMeshId = 0;
  42923. this.pickedSprite = null;
  42924. }
  42925. // Methods
  42926. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42927. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42928. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42929. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42930. return null;
  42931. }
  42932. var indices = this.pickedMesh.getIndices();
  42933. if (!indices) {
  42934. return null;
  42935. }
  42936. var result;
  42937. if (useVerticesNormals) {
  42938. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42939. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42940. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42941. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42942. normal0 = normal0.scale(this.bu);
  42943. normal1 = normal1.scale(this.bv);
  42944. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42945. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42946. }
  42947. else {
  42948. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42949. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42950. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42951. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42952. var p1p2 = vertex1.subtract(vertex2);
  42953. var p3p2 = vertex3.subtract(vertex2);
  42954. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42955. }
  42956. if (useWorldCoordinates) {
  42957. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42958. }
  42959. return BABYLON.Vector3.Normalize(result);
  42960. };
  42961. PickingInfo.prototype.getTextureCoordinates = function () {
  42962. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42963. return null;
  42964. }
  42965. var indices = this.pickedMesh.getIndices();
  42966. if (!indices) {
  42967. return null;
  42968. }
  42969. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42970. if (!uvs) {
  42971. return null;
  42972. }
  42973. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42974. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42975. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42976. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42977. uv1 = uv1.scale(this.bu);
  42978. uv2 = uv2.scale(this.bv);
  42979. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42980. };
  42981. return PickingInfo;
  42982. }());
  42983. BABYLON.PickingInfo = PickingInfo;
  42984. })(BABYLON || (BABYLON = {}));
  42985. //# sourceMappingURL=babylon.pickingInfo.js.map
  42986. var BABYLON;
  42987. (function (BABYLON) {
  42988. var Ray = /** @class */ (function () {
  42989. function Ray(origin, direction, length) {
  42990. if (length === void 0) { length = Number.MAX_VALUE; }
  42991. this.origin = origin;
  42992. this.direction = direction;
  42993. this.length = length;
  42994. }
  42995. // Methods
  42996. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42997. var d = 0.0;
  42998. var maxValue = Number.MAX_VALUE;
  42999. var inv;
  43000. var min;
  43001. var max;
  43002. var temp;
  43003. if (Math.abs(this.direction.x) < 0.0000001) {
  43004. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43005. return false;
  43006. }
  43007. }
  43008. else {
  43009. inv = 1.0 / this.direction.x;
  43010. min = (minimum.x - this.origin.x) * inv;
  43011. max = (maximum.x - this.origin.x) * inv;
  43012. if (max === -Infinity) {
  43013. max = Infinity;
  43014. }
  43015. if (min > max) {
  43016. temp = min;
  43017. min = max;
  43018. max = temp;
  43019. }
  43020. d = Math.max(min, d);
  43021. maxValue = Math.min(max, maxValue);
  43022. if (d > maxValue) {
  43023. return false;
  43024. }
  43025. }
  43026. if (Math.abs(this.direction.y) < 0.0000001) {
  43027. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43028. return false;
  43029. }
  43030. }
  43031. else {
  43032. inv = 1.0 / this.direction.y;
  43033. min = (minimum.y - this.origin.y) * inv;
  43034. max = (maximum.y - this.origin.y) * inv;
  43035. if (max === -Infinity) {
  43036. max = Infinity;
  43037. }
  43038. if (min > max) {
  43039. temp = min;
  43040. min = max;
  43041. max = temp;
  43042. }
  43043. d = Math.max(min, d);
  43044. maxValue = Math.min(max, maxValue);
  43045. if (d > maxValue) {
  43046. return false;
  43047. }
  43048. }
  43049. if (Math.abs(this.direction.z) < 0.0000001) {
  43050. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43051. return false;
  43052. }
  43053. }
  43054. else {
  43055. inv = 1.0 / this.direction.z;
  43056. min = (minimum.z - this.origin.z) * inv;
  43057. max = (maximum.z - this.origin.z) * inv;
  43058. if (max === -Infinity) {
  43059. max = Infinity;
  43060. }
  43061. if (min > max) {
  43062. temp = min;
  43063. min = max;
  43064. max = temp;
  43065. }
  43066. d = Math.max(min, d);
  43067. maxValue = Math.min(max, maxValue);
  43068. if (d > maxValue) {
  43069. return false;
  43070. }
  43071. }
  43072. return true;
  43073. };
  43074. Ray.prototype.intersectsBox = function (box) {
  43075. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43076. };
  43077. Ray.prototype.intersectsSphere = function (sphere) {
  43078. var x = sphere.center.x - this.origin.x;
  43079. var y = sphere.center.y - this.origin.y;
  43080. var z = sphere.center.z - this.origin.z;
  43081. var pyth = (x * x) + (y * y) + (z * z);
  43082. var rr = sphere.radius * sphere.radius;
  43083. if (pyth <= rr) {
  43084. return true;
  43085. }
  43086. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43087. if (dot < 0.0) {
  43088. return false;
  43089. }
  43090. var temp = pyth - (dot * dot);
  43091. return temp <= rr;
  43092. };
  43093. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43094. if (!this._edge1) {
  43095. this._edge1 = BABYLON.Vector3.Zero();
  43096. this._edge2 = BABYLON.Vector3.Zero();
  43097. this._pvec = BABYLON.Vector3.Zero();
  43098. this._tvec = BABYLON.Vector3.Zero();
  43099. this._qvec = BABYLON.Vector3.Zero();
  43100. }
  43101. vertex1.subtractToRef(vertex0, this._edge1);
  43102. vertex2.subtractToRef(vertex0, this._edge2);
  43103. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43104. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43105. if (det === 0) {
  43106. return null;
  43107. }
  43108. var invdet = 1 / det;
  43109. this.origin.subtractToRef(vertex0, this._tvec);
  43110. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43111. if (bu < 0 || bu > 1.0) {
  43112. return null;
  43113. }
  43114. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43115. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43116. if (bv < 0 || bu + bv > 1.0) {
  43117. return null;
  43118. }
  43119. //check if the distance is longer than the predefined length.
  43120. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43121. if (distance > this.length) {
  43122. return null;
  43123. }
  43124. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43125. };
  43126. Ray.prototype.intersectsPlane = function (plane) {
  43127. var distance;
  43128. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43129. if (Math.abs(result1) < 9.99999997475243E-07) {
  43130. return null;
  43131. }
  43132. else {
  43133. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43134. distance = (-plane.d - result2) / result1;
  43135. if (distance < 0.0) {
  43136. if (distance < -9.99999997475243E-07) {
  43137. return null;
  43138. }
  43139. else {
  43140. return 0;
  43141. }
  43142. }
  43143. return distance;
  43144. }
  43145. };
  43146. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43147. var tm = BABYLON.Tmp.Matrix[0];
  43148. mesh.getWorldMatrix().invertToRef(tm);
  43149. if (this._tmpRay) {
  43150. Ray.TransformToRef(this, tm, this._tmpRay);
  43151. }
  43152. else {
  43153. this._tmpRay = Ray.Transform(this, tm);
  43154. }
  43155. return mesh.intersects(this._tmpRay, fastCheck);
  43156. };
  43157. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43158. if (results) {
  43159. results.length = 0;
  43160. }
  43161. else {
  43162. results = [];
  43163. }
  43164. for (var i = 0; i < meshes.length; i++) {
  43165. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43166. if (pickInfo.hit) {
  43167. results.push(pickInfo);
  43168. }
  43169. }
  43170. results.sort(this._comparePickingInfo);
  43171. return results;
  43172. };
  43173. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43174. if (pickingInfoA.distance < pickingInfoB.distance) {
  43175. return -1;
  43176. }
  43177. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43178. return 1;
  43179. }
  43180. else {
  43181. return 0;
  43182. }
  43183. };
  43184. /**
  43185. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43186. * @param sega the first point of the segment to test the intersection against
  43187. * @param segb the second point of the segment to test the intersection against
  43188. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43189. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43190. */
  43191. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43192. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43193. var u = segb.subtract(sega);
  43194. var v = rsegb.subtract(this.origin);
  43195. var w = sega.subtract(this.origin);
  43196. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43197. var b = BABYLON.Vector3.Dot(u, v);
  43198. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43199. var d = BABYLON.Vector3.Dot(u, w);
  43200. var e = BABYLON.Vector3.Dot(v, w);
  43201. var D = a * c - b * b; // always >= 0
  43202. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43203. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43204. // compute the line parameters of the two closest points
  43205. if (D < Ray.smallnum) {
  43206. sN = 0.0; // force using point P0 on segment S1
  43207. sD = 1.0; // to prevent possible division by 0.0 later
  43208. tN = e;
  43209. tD = c;
  43210. }
  43211. else {
  43212. sN = (b * e - c * d);
  43213. tN = (a * e - b * d);
  43214. if (sN < 0.0) {
  43215. sN = 0.0;
  43216. tN = e;
  43217. tD = c;
  43218. }
  43219. else if (sN > sD) {
  43220. sN = sD;
  43221. tN = e + b;
  43222. tD = c;
  43223. }
  43224. }
  43225. if (tN < 0.0) {
  43226. tN = 0.0;
  43227. // recompute sc for this edge
  43228. if (-d < 0.0) {
  43229. sN = 0.0;
  43230. }
  43231. else if (-d > a)
  43232. sN = sD;
  43233. else {
  43234. sN = -d;
  43235. sD = a;
  43236. }
  43237. }
  43238. else if (tN > tD) {
  43239. tN = tD;
  43240. // recompute sc for this edge
  43241. if ((-d + b) < 0.0) {
  43242. sN = 0;
  43243. }
  43244. else if ((-d + b) > a) {
  43245. sN = sD;
  43246. }
  43247. else {
  43248. sN = (-d + b);
  43249. sD = a;
  43250. }
  43251. }
  43252. // finally do the division to get sc and tc
  43253. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43254. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43255. // get the difference of the two closest points
  43256. var qtc = v.multiplyByFloats(tc, tc, tc);
  43257. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43258. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43259. if (isIntersected) {
  43260. return qtc.length();
  43261. }
  43262. return -1;
  43263. };
  43264. // Statics
  43265. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43266. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43267. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43268. var direction = end.subtract(start);
  43269. direction.normalize();
  43270. return new Ray(start, direction);
  43271. };
  43272. /**
  43273. * 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
  43274. * transformed to the given world matrix.
  43275. * @param origin The origin point
  43276. * @param end The end point
  43277. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43278. */
  43279. Ray.CreateNewFromTo = function (origin, end, world) {
  43280. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43281. var direction = end.subtract(origin);
  43282. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43283. direction.normalize();
  43284. return Ray.Transform(new Ray(origin, direction, length), world);
  43285. };
  43286. Ray.Transform = function (ray, matrix) {
  43287. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43288. Ray.TransformToRef(ray, matrix, result);
  43289. return result;
  43290. };
  43291. Ray.TransformToRef = function (ray, matrix, result) {
  43292. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43293. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43294. result.length = ray.length;
  43295. var dir = result.direction;
  43296. var len = dir.length();
  43297. if (!(len === 0 || len === 1)) {
  43298. var num = 1.0 / len;
  43299. dir.x *= num;
  43300. dir.y *= num;
  43301. dir.z *= num;
  43302. result.length *= len;
  43303. }
  43304. };
  43305. Ray.smallnum = 0.00000001;
  43306. Ray.rayl = 10e8;
  43307. return Ray;
  43308. }());
  43309. BABYLON.Ray = Ray;
  43310. })(BABYLON || (BABYLON = {}));
  43311. //# sourceMappingURL=babylon.ray.js.map
  43312. var BABYLON;
  43313. (function (BABYLON) {
  43314. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43315. if (boxMin.x > sphereCenter.x + sphereRadius)
  43316. return false;
  43317. if (sphereCenter.x - sphereRadius > boxMax.x)
  43318. return false;
  43319. if (boxMin.y > sphereCenter.y + sphereRadius)
  43320. return false;
  43321. if (sphereCenter.y - sphereRadius > boxMax.y)
  43322. return false;
  43323. if (boxMin.z > sphereCenter.z + sphereRadius)
  43324. return false;
  43325. if (sphereCenter.z - sphereRadius > boxMax.z)
  43326. return false;
  43327. return true;
  43328. };
  43329. var getLowestRoot = (function () {
  43330. var result = { root: 0, found: false };
  43331. return function (a, b, c, maxR) {
  43332. result.root = 0;
  43333. result.found = false;
  43334. var determinant = b * b - 4.0 * a * c;
  43335. if (determinant < 0)
  43336. return result;
  43337. var sqrtD = Math.sqrt(determinant);
  43338. var r1 = (-b - sqrtD) / (2.0 * a);
  43339. var r2 = (-b + sqrtD) / (2.0 * a);
  43340. if (r1 > r2) {
  43341. var temp = r2;
  43342. r2 = r1;
  43343. r1 = temp;
  43344. }
  43345. if (r1 > 0 && r1 < maxR) {
  43346. result.root = r1;
  43347. result.found = true;
  43348. return result;
  43349. }
  43350. if (r2 > 0 && r2 < maxR) {
  43351. result.root = r2;
  43352. result.found = true;
  43353. return result;
  43354. }
  43355. return result;
  43356. };
  43357. })();
  43358. var Collider = /** @class */ (function () {
  43359. function Collider() {
  43360. this.radius = BABYLON.Vector3.One();
  43361. this.retry = 0;
  43362. this.basePointWorld = BABYLON.Vector3.Zero();
  43363. this.velocityWorld = BABYLON.Vector3.Zero();
  43364. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43365. this._collisionPoint = BABYLON.Vector3.Zero();
  43366. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43367. this._tempVector = BABYLON.Vector3.Zero();
  43368. this._tempVector2 = BABYLON.Vector3.Zero();
  43369. this._tempVector3 = BABYLON.Vector3.Zero();
  43370. this._tempVector4 = BABYLON.Vector3.Zero();
  43371. this._edge = BABYLON.Vector3.Zero();
  43372. this._baseToVertex = BABYLON.Vector3.Zero();
  43373. this._destinationPoint = BABYLON.Vector3.Zero();
  43374. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43375. this._displacementVector = BABYLON.Vector3.Zero();
  43376. this._collisionMask = -1;
  43377. }
  43378. Object.defineProperty(Collider.prototype, "collisionMask", {
  43379. get: function () {
  43380. return this._collisionMask;
  43381. },
  43382. set: function (mask) {
  43383. this._collisionMask = !isNaN(mask) ? mask : -1;
  43384. },
  43385. enumerable: true,
  43386. configurable: true
  43387. });
  43388. // Methods
  43389. Collider.prototype._initialize = function (source, dir, e) {
  43390. this.velocity = dir;
  43391. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43392. this.basePoint = source;
  43393. source.multiplyToRef(this.radius, this.basePointWorld);
  43394. dir.multiplyToRef(this.radius, this.velocityWorld);
  43395. this.velocityWorldLength = this.velocityWorld.length();
  43396. this.epsilon = e;
  43397. this.collisionFound = false;
  43398. };
  43399. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43400. pa.subtractToRef(point, this._tempVector);
  43401. pb.subtractToRef(point, this._tempVector2);
  43402. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43403. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43404. if (d < 0)
  43405. return false;
  43406. pc.subtractToRef(point, this._tempVector3);
  43407. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43408. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43409. if (d < 0)
  43410. return false;
  43411. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43412. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43413. return d >= 0;
  43414. };
  43415. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43416. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43417. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43418. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43419. return false;
  43420. }
  43421. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43422. return false;
  43423. return true;
  43424. };
  43425. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43426. var t0;
  43427. var embeddedInPlane = false;
  43428. //defensive programming, actually not needed.
  43429. if (!trianglePlaneArray) {
  43430. trianglePlaneArray = [];
  43431. }
  43432. if (!trianglePlaneArray[faceIndex]) {
  43433. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43434. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43435. }
  43436. var trianglePlane = trianglePlaneArray[faceIndex];
  43437. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43438. return;
  43439. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43440. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43441. if (normalDotVelocity == 0) {
  43442. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43443. return;
  43444. embeddedInPlane = true;
  43445. t0 = 0;
  43446. }
  43447. else {
  43448. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43449. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43450. if (t0 > t1) {
  43451. var temp = t1;
  43452. t1 = t0;
  43453. t0 = temp;
  43454. }
  43455. if (t0 > 1.0 || t1 < 0.0)
  43456. return;
  43457. if (t0 < 0)
  43458. t0 = 0;
  43459. if (t0 > 1.0)
  43460. t0 = 1.0;
  43461. }
  43462. this._collisionPoint.copyFromFloats(0, 0, 0);
  43463. var found = false;
  43464. var t = 1.0;
  43465. if (!embeddedInPlane) {
  43466. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43467. this.velocity.scaleToRef(t0, this._tempVector);
  43468. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43469. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43470. found = true;
  43471. t = t0;
  43472. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43473. }
  43474. }
  43475. if (!found) {
  43476. var velocitySquaredLength = this.velocity.lengthSquared();
  43477. var a = velocitySquaredLength;
  43478. this.basePoint.subtractToRef(p1, this._tempVector);
  43479. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43480. var c = this._tempVector.lengthSquared() - 1.0;
  43481. var lowestRoot = getLowestRoot(a, b, c, t);
  43482. if (lowestRoot.found) {
  43483. t = lowestRoot.root;
  43484. found = true;
  43485. this._collisionPoint.copyFrom(p1);
  43486. }
  43487. this.basePoint.subtractToRef(p2, this._tempVector);
  43488. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43489. c = this._tempVector.lengthSquared() - 1.0;
  43490. lowestRoot = getLowestRoot(a, b, c, t);
  43491. if (lowestRoot.found) {
  43492. t = lowestRoot.root;
  43493. found = true;
  43494. this._collisionPoint.copyFrom(p2);
  43495. }
  43496. this.basePoint.subtractToRef(p3, this._tempVector);
  43497. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43498. c = this._tempVector.lengthSquared() - 1.0;
  43499. lowestRoot = getLowestRoot(a, b, c, t);
  43500. if (lowestRoot.found) {
  43501. t = lowestRoot.root;
  43502. found = true;
  43503. this._collisionPoint.copyFrom(p3);
  43504. }
  43505. p2.subtractToRef(p1, this._edge);
  43506. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43507. var edgeSquaredLength = this._edge.lengthSquared();
  43508. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43509. var 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. var 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. p1.addToRef(this._edge, this._collisionPoint);
  43521. }
  43522. }
  43523. p3.subtractToRef(p2, this._edge);
  43524. p2.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. p2.addToRef(this._edge, this._collisionPoint);
  43539. }
  43540. }
  43541. p1.subtractToRef(p3, this._edge);
  43542. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43543. edgeSquaredLength = this._edge.lengthSquared();
  43544. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43545. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43546. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43547. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43548. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43549. lowestRoot = getLowestRoot(a, b, c, t);
  43550. if (lowestRoot.found) {
  43551. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43552. if (f >= 0.0 && f <= 1.0) {
  43553. t = lowestRoot.root;
  43554. found = true;
  43555. this._edge.scaleInPlace(f);
  43556. p3.addToRef(this._edge, this._collisionPoint);
  43557. }
  43558. }
  43559. }
  43560. if (found) {
  43561. var distToCollision = t * this.velocity.length();
  43562. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43563. if (!this.intersectionPoint) {
  43564. this.intersectionPoint = this._collisionPoint.clone();
  43565. }
  43566. else {
  43567. this.intersectionPoint.copyFrom(this._collisionPoint);
  43568. }
  43569. this.nearestDistance = distToCollision;
  43570. this.collisionFound = true;
  43571. }
  43572. }
  43573. };
  43574. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43575. for (var i = indexStart; i < indexEnd; i += 3) {
  43576. var p1 = pts[indices[i] - decal];
  43577. var p2 = pts[indices[i + 1] - decal];
  43578. var p3 = pts[indices[i + 2] - decal];
  43579. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43580. }
  43581. };
  43582. Collider.prototype._getResponse = function (pos, vel) {
  43583. pos.addToRef(vel, this._destinationPoint);
  43584. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43585. this.basePoint.addToRef(vel, pos);
  43586. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43587. this._slidePlaneNormal.normalize();
  43588. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43589. pos.addInPlace(this._displacementVector);
  43590. this.intersectionPoint.addInPlace(this._displacementVector);
  43591. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43592. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43593. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43594. };
  43595. return Collider;
  43596. }());
  43597. BABYLON.Collider = Collider;
  43598. })(BABYLON || (BABYLON = {}));
  43599. //# sourceMappingURL=babylon.collider.js.map
  43600. var BABYLON;
  43601. (function (BABYLON) {
  43602. //WebWorker code will be inserted to this variable.
  43603. BABYLON.CollisionWorker = "";
  43604. var WorkerTaskType;
  43605. (function (WorkerTaskType) {
  43606. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43607. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43608. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43609. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43610. var WorkerReplyType;
  43611. (function (WorkerReplyType) {
  43612. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43613. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43614. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43615. var CollisionCoordinatorWorker = /** @class */ (function () {
  43616. function CollisionCoordinatorWorker() {
  43617. var _this = this;
  43618. this._scaledPosition = BABYLON.Vector3.Zero();
  43619. this._scaledVelocity = BABYLON.Vector3.Zero();
  43620. this.onMeshUpdated = function (mesh) {
  43621. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43622. };
  43623. this.onGeometryUpdated = function (geometry) {
  43624. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43625. };
  43626. this._afterRender = function () {
  43627. if (!_this._init)
  43628. return;
  43629. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43630. return;
  43631. }
  43632. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43633. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43634. if (_this._runningUpdated > 4) {
  43635. return;
  43636. }
  43637. ++_this._runningUpdated;
  43638. var payload = {
  43639. updatedMeshes: _this._addUpdateMeshesList,
  43640. updatedGeometries: _this._addUpdateGeometriesList,
  43641. removedGeometries: _this._toRemoveGeometryArray,
  43642. removedMeshes: _this._toRemoveMeshesArray
  43643. };
  43644. var message = {
  43645. payload: payload,
  43646. taskType: WorkerTaskType.UPDATE
  43647. };
  43648. var serializable = [];
  43649. for (var id in payload.updatedGeometries) {
  43650. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43651. //prepare transferables
  43652. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43653. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43654. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43655. }
  43656. }
  43657. _this._worker.postMessage(message, serializable);
  43658. _this._addUpdateMeshesList = {};
  43659. _this._addUpdateGeometriesList = {};
  43660. _this._toRemoveGeometryArray = [];
  43661. _this._toRemoveMeshesArray = [];
  43662. };
  43663. this._onMessageFromWorker = function (e) {
  43664. var returnData = e.data;
  43665. if (returnData.error != WorkerReplyType.SUCCESS) {
  43666. //TODO what errors can be returned from the worker?
  43667. BABYLON.Tools.Warn("error returned from worker!");
  43668. return;
  43669. }
  43670. switch (returnData.taskType) {
  43671. case WorkerTaskType.INIT:
  43672. _this._init = true;
  43673. //Update the worked with ALL of the scene's current state
  43674. _this._scene.meshes.forEach(function (mesh) {
  43675. _this.onMeshAdded(mesh);
  43676. });
  43677. _this._scene.getGeometries().forEach(function (geometry) {
  43678. _this.onGeometryAdded(geometry);
  43679. });
  43680. break;
  43681. case WorkerTaskType.UPDATE:
  43682. _this._runningUpdated--;
  43683. break;
  43684. case WorkerTaskType.COLLIDE:
  43685. _this._runningCollisionTask = false;
  43686. var returnPayload = returnData.payload;
  43687. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43688. return;
  43689. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43690. if (callback) {
  43691. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43692. if (mesh) {
  43693. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43694. }
  43695. }
  43696. //cleanup
  43697. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43698. break;
  43699. }
  43700. };
  43701. this._collisionsCallbackArray = [];
  43702. this._init = false;
  43703. this._runningUpdated = 0;
  43704. this._runningCollisionTask = false;
  43705. this._addUpdateMeshesList = {};
  43706. this._addUpdateGeometriesList = {};
  43707. this._toRemoveGeometryArray = [];
  43708. this._toRemoveMeshesArray = [];
  43709. }
  43710. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43711. if (!this._init)
  43712. return;
  43713. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43714. return;
  43715. position.divideToRef(collider.radius, this._scaledPosition);
  43716. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43717. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43718. var payload = {
  43719. collider: {
  43720. position: this._scaledPosition.asArray(),
  43721. velocity: this._scaledVelocity.asArray(),
  43722. radius: collider.radius.asArray()
  43723. },
  43724. collisionId: collisionIndex,
  43725. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43726. maximumRetry: maximumRetry
  43727. };
  43728. var message = {
  43729. payload: payload,
  43730. taskType: WorkerTaskType.COLLIDE
  43731. };
  43732. this._worker.postMessage(message);
  43733. };
  43734. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43735. this._scene = scene;
  43736. this._scene.registerAfterRender(this._afterRender);
  43737. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43738. this._worker = new Worker(workerUrl);
  43739. this._worker.onmessage = this._onMessageFromWorker;
  43740. var message = {
  43741. payload: {},
  43742. taskType: WorkerTaskType.INIT
  43743. };
  43744. this._worker.postMessage(message);
  43745. };
  43746. CollisionCoordinatorWorker.prototype.destroy = function () {
  43747. this._scene.unregisterAfterRender(this._afterRender);
  43748. this._worker.terminate();
  43749. };
  43750. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43751. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43752. this.onMeshUpdated(mesh);
  43753. };
  43754. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43755. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43756. };
  43757. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43758. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43759. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43760. this.onGeometryUpdated(geometry);
  43761. };
  43762. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43763. this._toRemoveGeometryArray.push(geometry.id);
  43764. };
  43765. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43766. var submeshes = [];
  43767. if (mesh.subMeshes) {
  43768. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43769. var boundingInfo = sm.getBoundingInfo();
  43770. return {
  43771. position: idx,
  43772. verticesStart: sm.verticesStart,
  43773. verticesCount: sm.verticesCount,
  43774. indexStart: sm.indexStart,
  43775. indexCount: sm.indexCount,
  43776. hasMaterial: !!sm.getMaterial(),
  43777. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43778. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43779. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43780. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43781. };
  43782. });
  43783. }
  43784. var geometryId = null;
  43785. if (mesh instanceof BABYLON.Mesh) {
  43786. var geometry = mesh.geometry;
  43787. geometryId = geometry ? geometry.id : null;
  43788. }
  43789. else if (mesh instanceof BABYLON.InstancedMesh) {
  43790. var geometry = mesh.sourceMesh.geometry;
  43791. geometryId = geometry ? geometry.id : null;
  43792. }
  43793. var boundingInfo = mesh.getBoundingInfo();
  43794. return {
  43795. uniqueId: mesh.uniqueId,
  43796. id: mesh.id,
  43797. name: mesh.name,
  43798. geometryId: geometryId,
  43799. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43800. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43801. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43802. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43803. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43804. subMeshes: submeshes,
  43805. checkCollisions: mesh.checkCollisions
  43806. };
  43807. };
  43808. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43809. return {
  43810. id: geometry.id,
  43811. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43812. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43813. indices: new Uint32Array(geometry.getIndices() || []),
  43814. };
  43815. };
  43816. return CollisionCoordinatorWorker;
  43817. }());
  43818. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43819. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43820. function CollisionCoordinatorLegacy() {
  43821. this._scaledPosition = BABYLON.Vector3.Zero();
  43822. this._scaledVelocity = BABYLON.Vector3.Zero();
  43823. this._finalPosition = BABYLON.Vector3.Zero();
  43824. }
  43825. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43826. position.divideToRef(collider.radius, this._scaledPosition);
  43827. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43828. collider.collidedMesh = null;
  43829. collider.retry = 0;
  43830. collider.initialVelocity = this._scaledVelocity;
  43831. collider.initialPosition = this._scaledPosition;
  43832. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43833. this._finalPosition.multiplyInPlace(collider.radius);
  43834. //run the callback
  43835. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43836. };
  43837. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43838. this._scene = scene;
  43839. };
  43840. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43841. //Legacy need no destruction method.
  43842. };
  43843. //No update in legacy mode
  43844. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43845. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43846. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43847. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43848. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43849. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43850. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43851. if (excludedMesh === void 0) { excludedMesh = null; }
  43852. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43853. if (collider.retry >= maximumRetry) {
  43854. finalPosition.copyFrom(position);
  43855. return;
  43856. }
  43857. // Check if this is a mesh else camera or -1
  43858. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43859. collider._initialize(position, velocity, closeDistance);
  43860. // Check all meshes
  43861. for (var index = 0; index < this._scene.meshes.length; index++) {
  43862. var mesh = this._scene.meshes[index];
  43863. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43864. mesh._checkCollision(collider);
  43865. }
  43866. }
  43867. if (!collider.collisionFound) {
  43868. position.addToRef(velocity, finalPosition);
  43869. return;
  43870. }
  43871. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43872. collider._getResponse(position, velocity);
  43873. }
  43874. if (velocity.length() <= closeDistance) {
  43875. finalPosition.copyFrom(position);
  43876. return;
  43877. }
  43878. collider.retry++;
  43879. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43880. };
  43881. return CollisionCoordinatorLegacy;
  43882. }());
  43883. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43884. })(BABYLON || (BABYLON = {}));
  43885. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43886. var BABYLON;
  43887. (function (BABYLON) {
  43888. var Particle = /** @class */ (function () {
  43889. function Particle(particleSystem) {
  43890. this.particleSystem = particleSystem;
  43891. this.position = BABYLON.Vector3.Zero();
  43892. this.direction = BABYLON.Vector3.Zero();
  43893. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43894. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43895. this.lifeTime = 1.0;
  43896. this.age = 0;
  43897. this.size = 0;
  43898. this.angle = 0;
  43899. this.angularSpeed = 0;
  43900. this._currentFrameCounter = 0;
  43901. this.cellIndex = 0;
  43902. if (!this.particleSystem.isAnimationSheetEnabled) {
  43903. return;
  43904. }
  43905. this.cellIndex = this.particleSystem.startSpriteCellID;
  43906. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43907. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43908. }
  43909. else {
  43910. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43911. }
  43912. }
  43913. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43914. // (ageOffset / scaledUpdateSpeed) / available cells
  43915. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43916. this._currentFrameCounter += scaledUpdateSpeed;
  43917. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43918. this._currentFrameCounter = 0;
  43919. this.cellIndex++;
  43920. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43921. this.cellIndex = this.particleSystem.endSpriteCellID;
  43922. }
  43923. }
  43924. };
  43925. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43926. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43927. this.cellIndex++;
  43928. this._currentFrameCounter = 0;
  43929. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43930. if (this.particleSystem.spriteCellLoop) {
  43931. this.cellIndex = this.particleSystem.startSpriteCellID;
  43932. }
  43933. else {
  43934. this.cellIndex = this.particleSystem.endSpriteCellID;
  43935. }
  43936. }
  43937. }
  43938. else {
  43939. this._currentFrameCounter++;
  43940. }
  43941. };
  43942. Particle.prototype.copyTo = function (other) {
  43943. other.position.copyFrom(this.position);
  43944. other.direction.copyFrom(this.direction);
  43945. other.color.copyFrom(this.color);
  43946. other.colorStep.copyFrom(this.colorStep);
  43947. other.lifeTime = this.lifeTime;
  43948. other.age = this.age;
  43949. other.size = this.size;
  43950. other.angle = this.angle;
  43951. other.angularSpeed = this.angularSpeed;
  43952. other.particleSystem = this.particleSystem;
  43953. other.cellIndex = this.cellIndex;
  43954. };
  43955. return Particle;
  43956. }());
  43957. BABYLON.Particle = Particle;
  43958. })(BABYLON || (BABYLON = {}));
  43959. //# sourceMappingURL=babylon.particle.js.map
  43960. var BABYLON;
  43961. (function (BABYLON) {
  43962. var randomNumber = function (min, max) {
  43963. if (min === max) {
  43964. return (min);
  43965. }
  43966. var random = Math.random();
  43967. return ((random * (max - min)) + min);
  43968. };
  43969. var ParticleSystem = /** @class */ (function () {
  43970. // end of sheet animation
  43971. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43972. if (customEffect === void 0) { customEffect = null; }
  43973. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43974. if (epsilon === void 0) { epsilon = 0.01; }
  43975. var _this = this;
  43976. this.name = name;
  43977. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43978. // Members
  43979. this.animations = [];
  43980. this.renderingGroupId = 0;
  43981. this.emitter = null;
  43982. this.emitRate = 10;
  43983. this.manualEmitCount = -1;
  43984. this.updateSpeed = 0.01;
  43985. this.targetStopDuration = 0;
  43986. this.disposeOnStop = false;
  43987. this.minEmitPower = 1;
  43988. this.maxEmitPower = 1;
  43989. this.minLifeTime = 1;
  43990. this.maxLifeTime = 1;
  43991. this.minSize = 1;
  43992. this.maxSize = 1;
  43993. this.minAngularSpeed = 0;
  43994. this.maxAngularSpeed = 0;
  43995. this.layerMask = 0x0FFFFFFF;
  43996. this.customShader = null;
  43997. this.preventAutoStart = false;
  43998. /**
  43999. * An event triggered when the system is disposed.
  44000. * @type {BABYLON.Observable}
  44001. */
  44002. this.onDisposeObservable = new BABYLON.Observable();
  44003. this.onAnimationEnd = null;
  44004. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44005. this.forceDepthWrite = false;
  44006. this.gravity = BABYLON.Vector3.Zero();
  44007. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44008. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44009. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44010. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44011. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44012. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44013. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44014. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44015. this.particles = new Array();
  44016. this._stockParticles = new Array();
  44017. this._newPartsExcess = 0;
  44018. this._vertexBuffers = {};
  44019. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44020. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44021. this._scaledDirection = BABYLON.Vector3.Zero();
  44022. this._scaledGravity = BABYLON.Vector3.Zero();
  44023. this._currentRenderId = -1;
  44024. this._started = false;
  44025. this._stopped = false;
  44026. this._actualFrame = 0;
  44027. // sheet animation
  44028. this.startSpriteCellID = 0;
  44029. this.endSpriteCellID = 0;
  44030. this.spriteCellLoop = true;
  44031. this.spriteCellChangeSpeed = 0;
  44032. this.spriteCellWidth = 0;
  44033. this.spriteCellHeight = 0;
  44034. this._vertexBufferSize = 11;
  44035. this.appendParticleVertexes = null;
  44036. this.id = name;
  44037. this._capacity = capacity;
  44038. this._epsilon = epsilon;
  44039. if (_isAnimationSheetEnabled) {
  44040. this._vertexBufferSize = 12;
  44041. }
  44042. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44043. this._customEffect = customEffect;
  44044. scene.particleSystems.push(this);
  44045. this._createIndexBuffer();
  44046. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44047. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44048. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44049. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44050. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44051. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44052. if (this._isAnimationSheetEnabled) {
  44053. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44054. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44055. }
  44056. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44057. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44058. this._vertexBuffers["options"] = options;
  44059. // Default behaviors
  44060. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44061. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44062. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44063. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44064. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44065. };
  44066. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44067. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44068. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44069. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44070. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44071. };
  44072. this.updateFunction = function (particles) {
  44073. for (var index = 0; index < particles.length; index++) {
  44074. var particle = particles[index];
  44075. particle.age += _this._scaledUpdateSpeed;
  44076. if (particle.age >= particle.lifeTime) {
  44077. _this.recycleParticle(particle);
  44078. index--;
  44079. continue;
  44080. }
  44081. else {
  44082. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44083. particle.color.addInPlace(_this._scaledColorStep);
  44084. if (particle.color.a < 0)
  44085. particle.color.a = 0;
  44086. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44087. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44088. particle.position.addInPlace(_this._scaledDirection);
  44089. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44090. particle.direction.addInPlace(_this._scaledGravity);
  44091. if (_this._isAnimationSheetEnabled) {
  44092. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44093. }
  44094. }
  44095. }
  44096. };
  44097. }
  44098. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44099. set: function (callback) {
  44100. if (this._onDisposeObserver) {
  44101. this.onDisposeObservable.remove(this._onDisposeObserver);
  44102. }
  44103. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44104. },
  44105. enumerable: true,
  44106. configurable: true
  44107. });
  44108. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44109. get: function () {
  44110. return this._isAnimationSheetEnabled;
  44111. },
  44112. enumerable: true,
  44113. configurable: true
  44114. });
  44115. ParticleSystem.prototype._createIndexBuffer = function () {
  44116. var indices = [];
  44117. var index = 0;
  44118. for (var count = 0; count < this._capacity; count++) {
  44119. indices.push(index);
  44120. indices.push(index + 1);
  44121. indices.push(index + 2);
  44122. indices.push(index);
  44123. indices.push(index + 2);
  44124. indices.push(index + 3);
  44125. index += 4;
  44126. }
  44127. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44128. };
  44129. ParticleSystem.prototype.recycleParticle = function (particle) {
  44130. var lastParticle = this.particles.pop();
  44131. if (lastParticle !== particle) {
  44132. lastParticle.copyTo(particle);
  44133. this._stockParticles.push(lastParticle);
  44134. }
  44135. };
  44136. ParticleSystem.prototype.getCapacity = function () {
  44137. return this._capacity;
  44138. };
  44139. ParticleSystem.prototype.isAlive = function () {
  44140. return this._alive;
  44141. };
  44142. ParticleSystem.prototype.isStarted = function () {
  44143. return this._started;
  44144. };
  44145. ParticleSystem.prototype.start = function () {
  44146. this._started = true;
  44147. this._stopped = false;
  44148. this._actualFrame = 0;
  44149. };
  44150. ParticleSystem.prototype.stop = function () {
  44151. this._stopped = true;
  44152. };
  44153. // animation sheet
  44154. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44155. var offset = index * this._vertexBufferSize;
  44156. this._vertexData[offset] = particle.position.x;
  44157. this._vertexData[offset + 1] = particle.position.y;
  44158. this._vertexData[offset + 2] = particle.position.z;
  44159. this._vertexData[offset + 3] = particle.color.r;
  44160. this._vertexData[offset + 4] = particle.color.g;
  44161. this._vertexData[offset + 5] = particle.color.b;
  44162. this._vertexData[offset + 6] = particle.color.a;
  44163. this._vertexData[offset + 7] = particle.angle;
  44164. this._vertexData[offset + 8] = particle.size;
  44165. this._vertexData[offset + 9] = offsetX;
  44166. this._vertexData[offset + 10] = offsetY;
  44167. };
  44168. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44169. if (offsetX === 0)
  44170. offsetX = this._epsilon;
  44171. else if (offsetX === 1)
  44172. offsetX = 1 - this._epsilon;
  44173. if (offsetY === 0)
  44174. offsetY = this._epsilon;
  44175. else if (offsetY === 1)
  44176. offsetY = 1 - this._epsilon;
  44177. var offset = index * this._vertexBufferSize;
  44178. this._vertexData[offset] = particle.position.x;
  44179. this._vertexData[offset + 1] = particle.position.y;
  44180. this._vertexData[offset + 2] = particle.position.z;
  44181. this._vertexData[offset + 3] = particle.color.r;
  44182. this._vertexData[offset + 4] = particle.color.g;
  44183. this._vertexData[offset + 5] = particle.color.b;
  44184. this._vertexData[offset + 6] = particle.color.a;
  44185. this._vertexData[offset + 7] = particle.angle;
  44186. this._vertexData[offset + 8] = particle.size;
  44187. this._vertexData[offset + 9] = offsetX;
  44188. this._vertexData[offset + 10] = offsetY;
  44189. this._vertexData[offset + 11] = particle.cellIndex;
  44190. };
  44191. ParticleSystem.prototype._update = function (newParticles) {
  44192. // Update current
  44193. this._alive = this.particles.length > 0;
  44194. this.updateFunction(this.particles);
  44195. // Add new ones
  44196. var worldMatrix;
  44197. if (this.emitter.position) {
  44198. var emitterMesh = this.emitter;
  44199. worldMatrix = emitterMesh.getWorldMatrix();
  44200. }
  44201. else {
  44202. var emitterPosition = this.emitter;
  44203. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44204. }
  44205. var particle;
  44206. for (var index = 0; index < newParticles; index++) {
  44207. if (this.particles.length === this._capacity) {
  44208. break;
  44209. }
  44210. if (this._stockParticles.length !== 0) {
  44211. particle = this._stockParticles.pop();
  44212. particle.age = 0;
  44213. particle.cellIndex = this.startSpriteCellID;
  44214. }
  44215. else {
  44216. particle = new BABYLON.Particle(this);
  44217. }
  44218. this.particles.push(particle);
  44219. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44220. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44221. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44222. particle.size = randomNumber(this.minSize, this.maxSize);
  44223. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44224. this.startPositionFunction(worldMatrix, particle.position, particle);
  44225. var step = randomNumber(0, 1.0);
  44226. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44227. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44228. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44229. }
  44230. };
  44231. ParticleSystem.prototype._getEffect = function () {
  44232. if (this._customEffect) {
  44233. return this._customEffect;
  44234. }
  44235. ;
  44236. var defines = [];
  44237. if (this._scene.clipPlane) {
  44238. defines.push("#define CLIPPLANE");
  44239. }
  44240. if (this._isAnimationSheetEnabled) {
  44241. defines.push("#define ANIMATESHEET");
  44242. }
  44243. // Effect
  44244. var join = defines.join("\n");
  44245. if (this._cachedDefines !== join) {
  44246. this._cachedDefines = join;
  44247. var attributesNamesOrOptions;
  44248. var effectCreationOption;
  44249. if (this._isAnimationSheetEnabled) {
  44250. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44251. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44252. }
  44253. else {
  44254. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44255. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44256. }
  44257. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44258. }
  44259. return this._effect;
  44260. };
  44261. ParticleSystem.prototype.animate = function () {
  44262. if (!this._started)
  44263. return;
  44264. var effect = this._getEffect();
  44265. // Check
  44266. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44267. return;
  44268. if (this._currentRenderId === this._scene.getRenderId()) {
  44269. return;
  44270. }
  44271. this._currentRenderId = this._scene.getRenderId();
  44272. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44273. // determine the number of particles we need to create
  44274. var newParticles;
  44275. if (this.manualEmitCount > -1) {
  44276. newParticles = this.manualEmitCount;
  44277. this._newPartsExcess = 0;
  44278. this.manualEmitCount = 0;
  44279. }
  44280. else {
  44281. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44282. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44283. }
  44284. if (this._newPartsExcess > 1.0) {
  44285. newParticles += this._newPartsExcess >> 0;
  44286. this._newPartsExcess -= this._newPartsExcess >> 0;
  44287. }
  44288. this._alive = false;
  44289. if (!this._stopped) {
  44290. this._actualFrame += this._scaledUpdateSpeed;
  44291. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44292. this.stop();
  44293. }
  44294. else {
  44295. newParticles = 0;
  44296. }
  44297. this._update(newParticles);
  44298. // Stopped?
  44299. if (this._stopped) {
  44300. if (!this._alive) {
  44301. this._started = false;
  44302. if (this.onAnimationEnd) {
  44303. this.onAnimationEnd();
  44304. }
  44305. if (this.disposeOnStop) {
  44306. this._scene._toBeDisposed.push(this);
  44307. }
  44308. }
  44309. }
  44310. // Animation sheet
  44311. if (this._isAnimationSheetEnabled) {
  44312. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44313. }
  44314. else {
  44315. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44316. }
  44317. // Update VBO
  44318. var offset = 0;
  44319. for (var index = 0; index < this.particles.length; index++) {
  44320. var particle = this.particles[index];
  44321. this.appendParticleVertexes(offset, particle);
  44322. offset += 4;
  44323. }
  44324. if (this._vertexBuffer) {
  44325. this._vertexBuffer.update(this._vertexData);
  44326. }
  44327. };
  44328. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44329. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44330. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44331. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44332. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44333. };
  44334. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44335. this._appendParticleVertex(offset++, particle, 0, 0);
  44336. this._appendParticleVertex(offset++, particle, 1, 0);
  44337. this._appendParticleVertex(offset++, particle, 1, 1);
  44338. this._appendParticleVertex(offset++, particle, 0, 1);
  44339. };
  44340. ParticleSystem.prototype.rebuild = function () {
  44341. this._createIndexBuffer();
  44342. if (this._vertexBuffer) {
  44343. this._vertexBuffer._rebuild();
  44344. }
  44345. };
  44346. ParticleSystem.prototype.render = function () {
  44347. var effect = this._getEffect();
  44348. // Check
  44349. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44350. return 0;
  44351. var engine = this._scene.getEngine();
  44352. // Render
  44353. engine.enableEffect(effect);
  44354. engine.setState(false);
  44355. var viewMatrix = this._scene.getViewMatrix();
  44356. effect.setTexture("diffuseSampler", this.particleTexture);
  44357. effect.setMatrix("view", viewMatrix);
  44358. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44359. if (this._isAnimationSheetEnabled) {
  44360. var baseSize = this.particleTexture.getBaseSize();
  44361. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44362. }
  44363. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44364. if (this._scene.clipPlane) {
  44365. var clipPlane = this._scene.clipPlane;
  44366. var invView = viewMatrix.clone();
  44367. invView.invert();
  44368. effect.setMatrix("invView", invView);
  44369. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44370. }
  44371. // VBOs
  44372. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44373. // Draw order
  44374. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44375. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44376. }
  44377. else {
  44378. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44379. }
  44380. if (this.forceDepthWrite) {
  44381. engine.setDepthWrite(true);
  44382. }
  44383. engine.draw(true, 0, this.particles.length * 6);
  44384. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44385. return this.particles.length;
  44386. };
  44387. ParticleSystem.prototype.dispose = function () {
  44388. if (this._vertexBuffer) {
  44389. this._vertexBuffer.dispose();
  44390. this._vertexBuffer = null;
  44391. }
  44392. if (this._indexBuffer) {
  44393. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44394. this._indexBuffer = null;
  44395. }
  44396. if (this.particleTexture) {
  44397. this.particleTexture.dispose();
  44398. this.particleTexture = null;
  44399. }
  44400. // Remove from scene
  44401. var index = this._scene.particleSystems.indexOf(this);
  44402. if (index > -1) {
  44403. this._scene.particleSystems.splice(index, 1);
  44404. }
  44405. // Callback
  44406. this.onDisposeObservable.notifyObservers(this);
  44407. this.onDisposeObservable.clear();
  44408. };
  44409. // Clone
  44410. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44411. var custom = null;
  44412. var program = null;
  44413. if (this.customShader != null) {
  44414. program = this.customShader;
  44415. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44416. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44417. }
  44418. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44419. result.customShader = program;
  44420. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44421. if (newEmitter === undefined) {
  44422. newEmitter = this.emitter;
  44423. }
  44424. result.emitter = newEmitter;
  44425. if (this.particleTexture) {
  44426. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44427. }
  44428. if (!this.preventAutoStart) {
  44429. result.start();
  44430. }
  44431. return result;
  44432. };
  44433. ParticleSystem.prototype.serialize = function () {
  44434. var serializationObject = {};
  44435. serializationObject.name = this.name;
  44436. serializationObject.id = this.id;
  44437. // Emitter
  44438. if (this.emitter.position) {
  44439. var emitterMesh = this.emitter;
  44440. serializationObject.emitterId = emitterMesh.id;
  44441. }
  44442. else {
  44443. var emitterPosition = this.emitter;
  44444. serializationObject.emitter = emitterPosition.asArray();
  44445. }
  44446. serializationObject.capacity = this.getCapacity();
  44447. if (this.particleTexture) {
  44448. serializationObject.textureName = this.particleTexture.name;
  44449. }
  44450. // Animations
  44451. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44452. // Particle system
  44453. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44454. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44455. serializationObject.minSize = this.minSize;
  44456. serializationObject.maxSize = this.maxSize;
  44457. serializationObject.minEmitPower = this.minEmitPower;
  44458. serializationObject.maxEmitPower = this.maxEmitPower;
  44459. serializationObject.minLifeTime = this.minLifeTime;
  44460. serializationObject.maxLifeTime = this.maxLifeTime;
  44461. serializationObject.emitRate = this.emitRate;
  44462. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44463. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44464. serializationObject.gravity = this.gravity.asArray();
  44465. serializationObject.direction1 = this.direction1.asArray();
  44466. serializationObject.direction2 = this.direction2.asArray();
  44467. serializationObject.color1 = this.color1.asArray();
  44468. serializationObject.color2 = this.color2.asArray();
  44469. serializationObject.colorDead = this.colorDead.asArray();
  44470. serializationObject.updateSpeed = this.updateSpeed;
  44471. serializationObject.targetStopDuration = this.targetStopDuration;
  44472. serializationObject.textureMask = this.textureMask.asArray();
  44473. serializationObject.blendMode = this.blendMode;
  44474. serializationObject.customShader = this.customShader;
  44475. serializationObject.preventAutoStart = this.preventAutoStart;
  44476. return serializationObject;
  44477. };
  44478. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44479. var name = parsedParticleSystem.name;
  44480. var custom = null;
  44481. var program = null;
  44482. if (parsedParticleSystem.customShader) {
  44483. program = parsedParticleSystem.customShader;
  44484. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44485. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44486. }
  44487. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44488. particleSystem.customShader = program;
  44489. if (parsedParticleSystem.id) {
  44490. particleSystem.id = parsedParticleSystem.id;
  44491. }
  44492. // Auto start
  44493. if (parsedParticleSystem.preventAutoStart) {
  44494. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44495. }
  44496. // Texture
  44497. if (parsedParticleSystem.textureName) {
  44498. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44499. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44500. }
  44501. // Emitter
  44502. if (parsedParticleSystem.emitterId) {
  44503. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44504. }
  44505. else {
  44506. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44507. }
  44508. // Animations
  44509. if (parsedParticleSystem.animations) {
  44510. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44511. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44512. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44513. }
  44514. }
  44515. if (parsedParticleSystem.autoAnimate) {
  44516. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44517. }
  44518. // Particle system
  44519. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44520. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44521. particleSystem.minSize = parsedParticleSystem.minSize;
  44522. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44523. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44524. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44525. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44526. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44527. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44528. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44529. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44530. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44531. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44532. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44533. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44534. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44535. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44536. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44537. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44538. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44539. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44540. if (!particleSystem.preventAutoStart) {
  44541. particleSystem.start();
  44542. }
  44543. return particleSystem;
  44544. };
  44545. // Statics
  44546. ParticleSystem.BLENDMODE_ONEONE = 0;
  44547. ParticleSystem.BLENDMODE_STANDARD = 1;
  44548. return ParticleSystem;
  44549. }());
  44550. BABYLON.ParticleSystem = ParticleSystem;
  44551. })(BABYLON || (BABYLON = {}));
  44552. //# sourceMappingURL=babylon.particleSystem.js.map
  44553. var BABYLON;
  44554. (function (BABYLON) {
  44555. var SolidParticle = /** @class */ (function () {
  44556. /**
  44557. * Creates a Solid Particle object.
  44558. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44559. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44560. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44561. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44562. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44563. * `shapeId` (integer) is the model shape identifier in the SPS.
  44564. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44565. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44566. */
  44567. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44568. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44569. this.idx = 0; // particle global index
  44570. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44571. this.position = BABYLON.Vector3.Zero(); // position
  44572. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44573. this.scaling = BABYLON.Vector3.One(); // scaling
  44574. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44575. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44576. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44577. this.alive = true; // alive
  44578. this.isVisible = true; // visibility
  44579. this._pos = 0; // index of this particle in the global "positions" array
  44580. this._ind = 0; // index of this particle in the global "indices" array
  44581. this.shapeId = 0; // model shape id
  44582. this.idxInShape = 0; // index of the particle in its shape id
  44583. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44584. this.idx = particleIndex;
  44585. this._pos = positionIndex;
  44586. this._ind = indiceIndex;
  44587. this._model = model;
  44588. this.shapeId = shapeId;
  44589. this.idxInShape = idxInShape;
  44590. this._sps = sps;
  44591. if (modelBoundingInfo) {
  44592. this._modelBoundingInfo = modelBoundingInfo;
  44593. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44594. }
  44595. }
  44596. Object.defineProperty(SolidParticle.prototype, "scale", {
  44597. /**
  44598. * legacy support, changed scale to scaling
  44599. */
  44600. get: function () {
  44601. return this.scaling;
  44602. },
  44603. set: function (scale) {
  44604. this.scaling = scale;
  44605. },
  44606. enumerable: true,
  44607. configurable: true
  44608. });
  44609. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44610. /**
  44611. * legacy support, changed quaternion to rotationQuaternion
  44612. */
  44613. get: function () {
  44614. return this.rotationQuaternion;
  44615. },
  44616. set: function (q) {
  44617. this.rotationQuaternion = q;
  44618. },
  44619. enumerable: true,
  44620. configurable: true
  44621. });
  44622. /**
  44623. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44624. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44625. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44626. */
  44627. SolidParticle.prototype.intersectsMesh = function (target) {
  44628. if (!this._boundingInfo || !target._boundingInfo) {
  44629. return false;
  44630. }
  44631. if (this._sps._bSphereOnly) {
  44632. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44633. }
  44634. return this._boundingInfo.intersects(target._boundingInfo, false);
  44635. };
  44636. return SolidParticle;
  44637. }());
  44638. BABYLON.SolidParticle = SolidParticle;
  44639. var ModelShape = /** @class */ (function () {
  44640. /**
  44641. * 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.
  44642. * SPS internal tool, don't use it manually.
  44643. */
  44644. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44645. this._indicesLength = 0; // length of the shape in the model indices array
  44646. this.shapeID = id;
  44647. this._shape = shape;
  44648. this._indicesLength = indicesLength;
  44649. this._shapeUV = shapeUV;
  44650. this._positionFunction = posFunction;
  44651. this._vertexFunction = vtxFunction;
  44652. }
  44653. return ModelShape;
  44654. }());
  44655. BABYLON.ModelShape = ModelShape;
  44656. var DepthSortedParticle = /** @class */ (function () {
  44657. function DepthSortedParticle() {
  44658. this.ind = 0; // index of the particle in the "indices" array
  44659. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44660. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44661. }
  44662. return DepthSortedParticle;
  44663. }());
  44664. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44665. })(BABYLON || (BABYLON = {}));
  44666. //# sourceMappingURL=babylon.solidParticle.js.map
  44667. var BABYLON;
  44668. (function (BABYLON) {
  44669. /**
  44670. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44671. */
  44672. var SolidParticleSystem = /** @class */ (function () {
  44673. /**
  44674. * Creates a SPS (Solid Particle System) object.
  44675. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44676. * `scene` (Scene) is the scene in which the SPS is added.
  44677. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44678. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44679. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44680. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44681. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44682. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44683. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44684. */
  44685. function SolidParticleSystem(name, scene, options) {
  44686. // public members
  44687. /**
  44688. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44689. * Example : var p = SPS.particles[i];
  44690. */
  44691. this.particles = new Array();
  44692. /**
  44693. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44694. */
  44695. this.nbParticles = 0;
  44696. /**
  44697. * If the particles must ever face the camera (default false). Useful for planar particles.
  44698. */
  44699. this.billboard = false;
  44700. /**
  44701. * Recompute normals when adding a shape
  44702. */
  44703. this.recomputeNormals = true;
  44704. /**
  44705. * This a counter ofr your own usage. It's not set by any SPS functions.
  44706. */
  44707. this.counter = 0;
  44708. /**
  44709. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44710. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44711. */
  44712. this.vars = {};
  44713. this._positions = new Array();
  44714. this._indices = new Array();
  44715. this._normals = new Array();
  44716. this._colors = new Array();
  44717. this._uvs = new Array();
  44718. this._index = 0; // indices index
  44719. this._updatable = true;
  44720. this._pickable = false;
  44721. this._isVisibilityBoxLocked = false;
  44722. this._alwaysVisible = false;
  44723. this._depthSort = false;
  44724. this._shapeCounter = 0;
  44725. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44726. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44727. this._computeParticleColor = true;
  44728. this._computeParticleTexture = true;
  44729. this._computeParticleRotation = true;
  44730. this._computeParticleVertex = false;
  44731. this._computeBoundingBox = false;
  44732. this._depthSortParticles = true;
  44733. this._cam_axisZ = BABYLON.Vector3.Zero();
  44734. this._cam_axisY = BABYLON.Vector3.Zero();
  44735. this._cam_axisX = BABYLON.Vector3.Zero();
  44736. this._axisZ = BABYLON.Axis.Z;
  44737. this._camDir = BABYLON.Vector3.Zero();
  44738. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44739. this._rotMatrix = new BABYLON.Matrix();
  44740. this._invertMatrix = new BABYLON.Matrix();
  44741. this._rotated = BABYLON.Vector3.Zero();
  44742. this._quaternion = new BABYLON.Quaternion();
  44743. this._vertex = BABYLON.Vector3.Zero();
  44744. this._normal = BABYLON.Vector3.Zero();
  44745. this._yaw = 0.0;
  44746. this._pitch = 0.0;
  44747. this._roll = 0.0;
  44748. this._halfroll = 0.0;
  44749. this._halfpitch = 0.0;
  44750. this._halfyaw = 0.0;
  44751. this._sinRoll = 0.0;
  44752. this._cosRoll = 0.0;
  44753. this._sinPitch = 0.0;
  44754. this._cosPitch = 0.0;
  44755. this._sinYaw = 0.0;
  44756. this._cosYaw = 0.0;
  44757. this._mustUnrotateFixedNormals = false;
  44758. this._minimum = BABYLON.Tmp.Vector3[0];
  44759. this._maximum = BABYLON.Tmp.Vector3[1];
  44760. this._minBbox = BABYLON.Tmp.Vector3[4];
  44761. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44762. this._particlesIntersect = false;
  44763. this._depthSortFunction = function (p1, p2) {
  44764. return (p2.sqDistance - p1.sqDistance);
  44765. };
  44766. this._needs32Bits = false;
  44767. this._bSphereOnly = false;
  44768. this._bSphereRadiusFactor = 1.0;
  44769. this.name = name;
  44770. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44771. this._camera = scene.activeCamera;
  44772. this._pickable = options ? options.isPickable : false;
  44773. this._depthSort = options ? options.enableDepthSort : false;
  44774. this._particlesIntersect = options ? options.particleIntersection : false;
  44775. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44776. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44777. if (options && options.updatable) {
  44778. this._updatable = options.updatable;
  44779. }
  44780. else {
  44781. this._updatable = true;
  44782. }
  44783. if (this._pickable) {
  44784. this.pickedParticles = [];
  44785. }
  44786. if (this._depthSort) {
  44787. this.depthSortedParticles = [];
  44788. }
  44789. }
  44790. /**
  44791. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44792. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44793. */
  44794. SolidParticleSystem.prototype.buildMesh = function () {
  44795. if (this.nbParticles === 0) {
  44796. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44797. this.addShape(triangle, 1);
  44798. triangle.dispose();
  44799. }
  44800. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44801. this._positions32 = new Float32Array(this._positions);
  44802. this._uvs32 = new Float32Array(this._uvs);
  44803. this._colors32 = new Float32Array(this._colors);
  44804. if (this.recomputeNormals) {
  44805. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44806. }
  44807. this._normals32 = new Float32Array(this._normals);
  44808. this._fixedNormal32 = new Float32Array(this._normals);
  44809. if (this._mustUnrotateFixedNormals) {
  44810. this._unrotateFixedNormals();
  44811. }
  44812. var vertexData = new BABYLON.VertexData();
  44813. vertexData.indices = this._indices32;
  44814. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44815. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44816. if (this._uvs32) {
  44817. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44818. ;
  44819. }
  44820. if (this._colors32) {
  44821. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44822. }
  44823. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44824. vertexData.applyToMesh(mesh, this._updatable);
  44825. this.mesh = mesh;
  44826. this.mesh.isPickable = this._pickable;
  44827. // free memory
  44828. if (!this._depthSort) {
  44829. this._indices = null;
  44830. }
  44831. this._positions = null;
  44832. this._normals = null;
  44833. this._uvs = null;
  44834. this._colors = null;
  44835. if (!this._updatable) {
  44836. this.particles.length = 0;
  44837. }
  44838. return mesh;
  44839. };
  44840. /**
  44841. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44842. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44843. * Thus the particles generated from `digest()` have their property `position` set yet.
  44844. * `mesh` ( Mesh ) is the mesh to be digested
  44845. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44846. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44847. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44848. */
  44849. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44850. var size = (options && options.facetNb) || 1;
  44851. var number = (options && options.number) || 0;
  44852. var delta = (options && options.delta) || 0;
  44853. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44854. var meshInd = mesh.getIndices();
  44855. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44856. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44857. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44858. var f = 0; // facet counter
  44859. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44860. // compute size from number
  44861. if (number) {
  44862. number = (number > totalFacets) ? totalFacets : number;
  44863. size = Math.round(totalFacets / number);
  44864. delta = 0;
  44865. }
  44866. else {
  44867. size = (size > totalFacets) ? totalFacets : size;
  44868. }
  44869. var facetPos = []; // submesh positions
  44870. var facetInd = []; // submesh indices
  44871. var facetUV = []; // submesh UV
  44872. var facetCol = []; // submesh colors
  44873. var barycenter = BABYLON.Tmp.Vector3[0];
  44874. var sizeO = size;
  44875. while (f < totalFacets) {
  44876. size = sizeO + Math.floor((1 + delta) * Math.random());
  44877. if (f > totalFacets - size) {
  44878. size = totalFacets - f;
  44879. }
  44880. // reset temp arrays
  44881. facetPos.length = 0;
  44882. facetInd.length = 0;
  44883. facetUV.length = 0;
  44884. facetCol.length = 0;
  44885. // iterate over "size" facets
  44886. var fi = 0;
  44887. for (var j = f * 3; j < (f + size) * 3; j++) {
  44888. facetInd.push(fi);
  44889. var i = meshInd[j];
  44890. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44891. if (meshUV) {
  44892. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44893. }
  44894. if (meshCol) {
  44895. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44896. }
  44897. fi++;
  44898. }
  44899. // create a model shape for each single particle
  44900. var idx = this.nbParticles;
  44901. var shape = this._posToShape(facetPos);
  44902. var shapeUV = this._uvsToShapeUV(facetUV);
  44903. // compute the barycenter of the shape
  44904. var v;
  44905. for (v = 0; v < shape.length; v++) {
  44906. barycenter.addInPlace(shape[v]);
  44907. }
  44908. barycenter.scaleInPlace(1 / shape.length);
  44909. // shift the shape from its barycenter to the origin
  44910. for (v = 0; v < shape.length; v++) {
  44911. shape[v].subtractInPlace(barycenter);
  44912. }
  44913. var bInfo;
  44914. if (this._particlesIntersect) {
  44915. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44916. }
  44917. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44918. // add the particle in the SPS
  44919. var currentPos = this._positions.length;
  44920. var currentInd = this._indices.length;
  44921. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44922. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44923. // initialize the particle position
  44924. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44925. this._index += shape.length;
  44926. idx++;
  44927. this.nbParticles++;
  44928. this._shapeCounter++;
  44929. f += size;
  44930. }
  44931. return this;
  44932. };
  44933. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44934. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44935. var index = 0;
  44936. var idx = 0;
  44937. for (var p = 0; p < this.particles.length; p++) {
  44938. this._particle = this.particles[p];
  44939. this._shape = this._particle._model._shape;
  44940. if (this._particle.rotationQuaternion) {
  44941. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44942. }
  44943. else {
  44944. this._yaw = this._particle.rotation.y;
  44945. this._pitch = this._particle.rotation.x;
  44946. this._roll = this._particle.rotation.z;
  44947. this._quaternionRotationYPR();
  44948. }
  44949. this._quaternionToRotationMatrix();
  44950. this._rotMatrix.invertToRef(this._invertMatrix);
  44951. for (var pt = 0; pt < this._shape.length; pt++) {
  44952. idx = index + pt * 3;
  44953. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44954. this._fixedNormal32[idx] = this._normal.x;
  44955. this._fixedNormal32[idx + 1] = this._normal.y;
  44956. this._fixedNormal32[idx + 2] = this._normal.z;
  44957. }
  44958. index = idx + 3;
  44959. }
  44960. };
  44961. //reset copy
  44962. SolidParticleSystem.prototype._resetCopy = function () {
  44963. this._copy.position.x = 0;
  44964. this._copy.position.y = 0;
  44965. this._copy.position.z = 0;
  44966. this._copy.rotation.x = 0;
  44967. this._copy.rotation.y = 0;
  44968. this._copy.rotation.z = 0;
  44969. this._copy.rotationQuaternion = null;
  44970. this._copy.scaling.x = 1.0;
  44971. this._copy.scaling.y = 1.0;
  44972. this._copy.scaling.z = 1.0;
  44973. this._copy.uvs.x = 0;
  44974. this._copy.uvs.y = 0;
  44975. this._copy.uvs.z = 1.0;
  44976. this._copy.uvs.w = 1.0;
  44977. this._copy.color = null;
  44978. };
  44979. // _meshBuilder : inserts the shape model in the global SPS mesh
  44980. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44981. var i;
  44982. var u = 0;
  44983. var c = 0;
  44984. var n = 0;
  44985. this._resetCopy();
  44986. if (options && options.positionFunction) {
  44987. options.positionFunction(this._copy, idx, idxInShape);
  44988. this._mustUnrotateFixedNormals = true;
  44989. }
  44990. if (this._copy.rotationQuaternion) {
  44991. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44992. }
  44993. else {
  44994. this._yaw = this._copy.rotation.y;
  44995. this._pitch = this._copy.rotation.x;
  44996. this._roll = this._copy.rotation.z;
  44997. this._quaternionRotationYPR();
  44998. }
  44999. this._quaternionToRotationMatrix();
  45000. for (i = 0; i < shape.length; i++) {
  45001. this._vertex.x = shape[i].x;
  45002. this._vertex.y = shape[i].y;
  45003. this._vertex.z = shape[i].z;
  45004. if (options && options.vertexFunction) {
  45005. options.vertexFunction(this._copy, this._vertex, i);
  45006. }
  45007. this._vertex.x *= this._copy.scaling.x;
  45008. this._vertex.y *= this._copy.scaling.y;
  45009. this._vertex.z *= this._copy.scaling.z;
  45010. this._vertex.x += this._copy.pivot.x;
  45011. this._vertex.y += this._copy.pivot.y;
  45012. this._vertex.z += this._copy.pivot.z;
  45013. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45014. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45015. if (meshUV) {
  45016. 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);
  45017. u += 2;
  45018. }
  45019. if (this._copy.color) {
  45020. this._color = this._copy.color;
  45021. }
  45022. else if (meshCol && meshCol[c] !== undefined) {
  45023. this._color.r = meshCol[c];
  45024. this._color.g = meshCol[c + 1];
  45025. this._color.b = meshCol[c + 2];
  45026. this._color.a = meshCol[c + 3];
  45027. }
  45028. else {
  45029. this._color.r = 1.0;
  45030. this._color.g = 1.0;
  45031. this._color.b = 1.0;
  45032. this._color.a = 1.0;
  45033. }
  45034. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45035. c += 4;
  45036. if (!this.recomputeNormals && meshNor) {
  45037. this._normal.x = meshNor[n];
  45038. this._normal.y = meshNor[n + 1];
  45039. this._normal.z = meshNor[n + 2];
  45040. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45041. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45042. n += 3;
  45043. }
  45044. }
  45045. for (i = 0; i < meshInd.length; i++) {
  45046. var current_ind = p + meshInd[i];
  45047. indices.push(current_ind);
  45048. if (current_ind > 65535) {
  45049. this._needs32Bits = true;
  45050. }
  45051. }
  45052. if (this._pickable) {
  45053. var nbfaces = meshInd.length / 3;
  45054. for (i = 0; i < nbfaces; i++) {
  45055. this.pickedParticles.push({ idx: idx, faceId: i });
  45056. }
  45057. }
  45058. if (this._depthSort) {
  45059. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45060. }
  45061. return this._copy;
  45062. };
  45063. // returns a shape array from positions array
  45064. SolidParticleSystem.prototype._posToShape = function (positions) {
  45065. var shape = [];
  45066. for (var i = 0; i < positions.length; i += 3) {
  45067. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45068. }
  45069. return shape;
  45070. };
  45071. // returns a shapeUV array from a Vector4 uvs
  45072. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45073. var shapeUV = [];
  45074. if (uvs) {
  45075. for (var i = 0; i < uvs.length; i++)
  45076. shapeUV.push(uvs[i]);
  45077. }
  45078. return shapeUV;
  45079. };
  45080. // adds a new particle object in the particles array
  45081. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45082. if (bInfo === void 0) { bInfo = null; }
  45083. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45084. this.particles.push(sp);
  45085. return sp;
  45086. };
  45087. /**
  45088. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45089. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45090. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45091. * `nb` (positive integer) the number of particles to be created from this model
  45092. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45093. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45094. */
  45095. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45096. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45097. var meshInd = mesh.getIndices();
  45098. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45099. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45100. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45101. var bbInfo;
  45102. if (this._particlesIntersect) {
  45103. bbInfo = mesh.getBoundingInfo();
  45104. }
  45105. var shape = this._posToShape(meshPos);
  45106. var shapeUV = this._uvsToShapeUV(meshUV);
  45107. var posfunc = options ? options.positionFunction : null;
  45108. var vtxfunc = options ? options.vertexFunction : null;
  45109. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45110. // particles
  45111. var sp;
  45112. var currentCopy;
  45113. var idx = this.nbParticles;
  45114. for (var i = 0; i < nb; i++) {
  45115. var currentPos = this._positions.length;
  45116. var currentInd = this._indices.length;
  45117. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45118. if (this._updatable) {
  45119. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45120. sp.position.copyFrom(currentCopy.position);
  45121. sp.rotation.copyFrom(currentCopy.rotation);
  45122. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45123. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45124. }
  45125. if (currentCopy.color && sp.color) {
  45126. sp.color.copyFrom(currentCopy.color);
  45127. }
  45128. sp.scaling.copyFrom(currentCopy.scaling);
  45129. sp.uvs.copyFrom(currentCopy.uvs);
  45130. }
  45131. this._index += shape.length;
  45132. idx++;
  45133. }
  45134. this.nbParticles += nb;
  45135. this._shapeCounter++;
  45136. return this._shapeCounter - 1;
  45137. };
  45138. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45139. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45140. this._resetCopy();
  45141. if (particle._model._positionFunction) {
  45142. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45143. }
  45144. if (this._copy.rotationQuaternion) {
  45145. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45146. }
  45147. else {
  45148. this._yaw = this._copy.rotation.y;
  45149. this._pitch = this._copy.rotation.x;
  45150. this._roll = this._copy.rotation.z;
  45151. this._quaternionRotationYPR();
  45152. }
  45153. this._quaternionToRotationMatrix();
  45154. this._shape = particle._model._shape;
  45155. for (var pt = 0; pt < this._shape.length; pt++) {
  45156. this._vertex.x = this._shape[pt].x;
  45157. this._vertex.y = this._shape[pt].y;
  45158. this._vertex.z = this._shape[pt].z;
  45159. if (particle._model._vertexFunction) {
  45160. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45161. }
  45162. this._vertex.x *= this._copy.scaling.x;
  45163. this._vertex.y *= this._copy.scaling.y;
  45164. this._vertex.z *= this._copy.scaling.z;
  45165. this._vertex.x += this._copy.pivot.x;
  45166. this._vertex.y += this._copy.pivot.y;
  45167. this._vertex.z += this._copy.pivot.z;
  45168. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45169. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45170. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45171. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45172. }
  45173. particle.position.x = 0.0;
  45174. particle.position.y = 0.0;
  45175. particle.position.z = 0.0;
  45176. particle.rotation.x = 0.0;
  45177. particle.rotation.y = 0.0;
  45178. particle.rotation.z = 0.0;
  45179. particle.rotationQuaternion = null;
  45180. particle.scaling.x = 1.0;
  45181. particle.scaling.y = 1.0;
  45182. particle.scaling.z = 1.0;
  45183. };
  45184. /**
  45185. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45186. * Returns the SPS.
  45187. */
  45188. SolidParticleSystem.prototype.rebuildMesh = function () {
  45189. for (var p = 0; p < this.particles.length; p++) {
  45190. this._rebuildParticle(this.particles[p]);
  45191. }
  45192. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45193. return this;
  45194. };
  45195. /**
  45196. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45197. * This method calls `updateParticle()` for each particle of the SPS.
  45198. * For an animated SPS, it is usually called within the render loop.
  45199. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45200. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45201. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45202. * Returns the SPS.
  45203. */
  45204. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45205. if (start === void 0) { start = 0; }
  45206. if (end === void 0) { end = this.nbParticles - 1; }
  45207. if (update === void 0) { update = true; }
  45208. if (!this._updatable) {
  45209. return this;
  45210. }
  45211. // custom beforeUpdate
  45212. this.beforeUpdateParticles(start, end, update);
  45213. this._cam_axisX.x = 1.0;
  45214. this._cam_axisX.y = 0.0;
  45215. this._cam_axisX.z = 0.0;
  45216. this._cam_axisY.x = 0.0;
  45217. this._cam_axisY.y = 1.0;
  45218. this._cam_axisY.z = 0.0;
  45219. this._cam_axisZ.x = 0.0;
  45220. this._cam_axisZ.y = 0.0;
  45221. this._cam_axisZ.z = 1.0;
  45222. // cases when the World Matrix is to be computed first
  45223. if (this.billboard || this._depthSort) {
  45224. this.mesh.computeWorldMatrix(true);
  45225. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45226. }
  45227. // if the particles will always face the camera
  45228. if (this.billboard) {
  45229. // compute the camera position and un-rotate it by the current mesh rotation
  45230. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45231. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45232. this._cam_axisZ.normalize();
  45233. // same for camera up vector extracted from the cam view matrix
  45234. var view = this._camera.getViewMatrix(true);
  45235. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45236. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45237. this._cam_axisY.normalize();
  45238. this._cam_axisX.normalize();
  45239. }
  45240. // if depthSort, compute the camera global position in the mesh local system
  45241. if (this._depthSort) {
  45242. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45243. }
  45244. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45245. var idx = 0; // current position index in the global array positions32
  45246. var index = 0; // position start index in the global array positions32 of the current particle
  45247. var colidx = 0; // current color index in the global array colors32
  45248. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45249. var uvidx = 0; // current uv index in the global array uvs32
  45250. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45251. var pt = 0; // current index in the particle model shape
  45252. if (this.mesh.isFacetDataEnabled) {
  45253. this._computeBoundingBox = true;
  45254. }
  45255. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45256. if (this._computeBoundingBox) {
  45257. if (start == 0 && end == this.nbParticles - 1) {
  45258. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45259. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45260. }
  45261. else {
  45262. if (this.mesh._boundingInfo) {
  45263. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45264. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45265. }
  45266. }
  45267. }
  45268. // particle loop
  45269. index = this.particles[start]._pos;
  45270. var vpos = (index / 3) | 0;
  45271. colorIndex = vpos * 4;
  45272. uvIndex = vpos * 2;
  45273. for (var p = start; p <= end; p++) {
  45274. this._particle = this.particles[p];
  45275. this._shape = this._particle._model._shape;
  45276. this._shapeUV = this._particle._model._shapeUV;
  45277. // call to custom user function to update the particle properties
  45278. this.updateParticle(this._particle);
  45279. // camera-particle distance for depth sorting
  45280. if (this._depthSort && this._depthSortParticles) {
  45281. var dsp = this.depthSortedParticles[p];
  45282. dsp.ind = this._particle._ind;
  45283. dsp.indicesLength = this._particle._model._indicesLength;
  45284. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45285. }
  45286. // skip the computations for inactive or already invisible particles
  45287. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45288. // increment indexes for the next particle
  45289. pt = this._shape.length;
  45290. index += pt * 3;
  45291. colorIndex += pt * 4;
  45292. uvIndex += pt * 2;
  45293. continue;
  45294. }
  45295. if (this._particle.isVisible) {
  45296. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45297. // particle rotation matrix
  45298. if (this.billboard) {
  45299. this._particle.rotation.x = 0.0;
  45300. this._particle.rotation.y = 0.0;
  45301. }
  45302. if (this._computeParticleRotation || this.billboard) {
  45303. if (this._particle.rotationQuaternion) {
  45304. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45305. }
  45306. else {
  45307. this._yaw = this._particle.rotation.y;
  45308. this._pitch = this._particle.rotation.x;
  45309. this._roll = this._particle.rotation.z;
  45310. this._quaternionRotationYPR();
  45311. }
  45312. this._quaternionToRotationMatrix();
  45313. }
  45314. // particle vertex loop
  45315. for (pt = 0; pt < this._shape.length; pt++) {
  45316. idx = index + pt * 3;
  45317. colidx = colorIndex + pt * 4;
  45318. uvidx = uvIndex + pt * 2;
  45319. this._vertex.x = this._shape[pt].x;
  45320. this._vertex.y = this._shape[pt].y;
  45321. this._vertex.z = this._shape[pt].z;
  45322. if (this._computeParticleVertex) {
  45323. this.updateParticleVertex(this._particle, this._vertex, pt);
  45324. }
  45325. // positions
  45326. this._vertex.x *= this._particle.scaling.x;
  45327. this._vertex.y *= this._particle.scaling.y;
  45328. this._vertex.z *= this._particle.scaling.z;
  45329. this._vertex.x += this._particle.pivot.x;
  45330. this._vertex.y += this._particle.pivot.y;
  45331. this._vertex.z += this._particle.pivot.z;
  45332. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45333. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45334. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45335. 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;
  45336. 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;
  45337. 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;
  45338. if (this._computeBoundingBox) {
  45339. if (this._positions32[idx] < this._minimum.x) {
  45340. this._minimum.x = this._positions32[idx];
  45341. }
  45342. if (this._positions32[idx] > this._maximum.x) {
  45343. this._maximum.x = this._positions32[idx];
  45344. }
  45345. if (this._positions32[idx + 1] < this._minimum.y) {
  45346. this._minimum.y = this._positions32[idx + 1];
  45347. }
  45348. if (this._positions32[idx + 1] > this._maximum.y) {
  45349. this._maximum.y = this._positions32[idx + 1];
  45350. }
  45351. if (this._positions32[idx + 2] < this._minimum.z) {
  45352. this._minimum.z = this._positions32[idx + 2];
  45353. }
  45354. if (this._positions32[idx + 2] > this._maximum.z) {
  45355. this._maximum.z = this._positions32[idx + 2];
  45356. }
  45357. }
  45358. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45359. if (!this._computeParticleVertex) {
  45360. this._normal.x = this._fixedNormal32[idx];
  45361. this._normal.y = this._fixedNormal32[idx + 1];
  45362. this._normal.z = this._fixedNormal32[idx + 2];
  45363. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45364. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45365. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45366. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45367. 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;
  45368. 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;
  45369. }
  45370. if (this._computeParticleColor && this._particle.color) {
  45371. this._colors32[colidx] = this._particle.color.r;
  45372. this._colors32[colidx + 1] = this._particle.color.g;
  45373. this._colors32[colidx + 2] = this._particle.color.b;
  45374. this._colors32[colidx + 3] = this._particle.color.a;
  45375. }
  45376. if (this._computeParticleTexture) {
  45377. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45378. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45379. }
  45380. }
  45381. }
  45382. else {
  45383. this._particle._stillInvisible = true; // mark the particle as invisible
  45384. for (pt = 0; pt < this._shape.length; pt++) {
  45385. idx = index + pt * 3;
  45386. colidx = colorIndex + pt * 4;
  45387. uvidx = uvIndex + pt * 2;
  45388. this._positions32[idx] = 0.0;
  45389. this._positions32[idx + 1] = 0.0;
  45390. this._positions32[idx + 2] = 0.0;
  45391. this._normals32[idx] = 0.0;
  45392. this._normals32[idx + 1] = 0.0;
  45393. this._normals32[idx + 2] = 0.0;
  45394. if (this._computeParticleColor && this._particle.color) {
  45395. this._colors32[colidx] = this._particle.color.r;
  45396. this._colors32[colidx + 1] = this._particle.color.g;
  45397. this._colors32[colidx + 2] = this._particle.color.b;
  45398. this._colors32[colidx + 3] = this._particle.color.a;
  45399. }
  45400. if (this._computeParticleTexture) {
  45401. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45402. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45403. }
  45404. }
  45405. }
  45406. // if the particle intersections must be computed : update the bbInfo
  45407. if (this._particlesIntersect) {
  45408. var bInfo = this._particle._boundingInfo;
  45409. var bBox = bInfo.boundingBox;
  45410. var bSphere = bInfo.boundingSphere;
  45411. if (!this._bSphereOnly) {
  45412. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45413. for (var b = 0; b < bBox.vectors.length; b++) {
  45414. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45415. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45416. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45417. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45418. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45419. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45420. 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;
  45421. 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;
  45422. 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;
  45423. }
  45424. bBox._update(this.mesh._worldMatrix);
  45425. }
  45426. // place and scale the particle bouding sphere in the SPS local system, then update it
  45427. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45428. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45429. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45430. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45431. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45432. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45433. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45434. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45435. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45436. 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));
  45437. bSphere._update(this.mesh._worldMatrix);
  45438. }
  45439. // increment indexes for the next particle
  45440. index = idx + 3;
  45441. colorIndex = colidx + 4;
  45442. uvIndex = uvidx + 2;
  45443. }
  45444. // if the VBO must be updated
  45445. if (update) {
  45446. if (this._computeParticleColor) {
  45447. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45448. }
  45449. if (this._computeParticleTexture) {
  45450. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45451. }
  45452. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45453. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45454. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45455. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45456. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45457. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45458. for (var i = 0; i < this._normals32.length; i++) {
  45459. this._fixedNormal32[i] = this._normals32[i];
  45460. }
  45461. }
  45462. if (!this.mesh.areNormalsFrozen) {
  45463. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45464. }
  45465. }
  45466. if (this._depthSort && this._depthSortParticles) {
  45467. this.depthSortedParticles.sort(this._depthSortFunction);
  45468. var dspl = this.depthSortedParticles.length;
  45469. var sorted = 0;
  45470. var lind = 0;
  45471. var sind = 0;
  45472. var sid = 0;
  45473. for (sorted = 0; sorted < dspl; sorted++) {
  45474. lind = this.depthSortedParticles[sorted].indicesLength;
  45475. sind = this.depthSortedParticles[sorted].ind;
  45476. for (var i = 0; i < lind; i++) {
  45477. this._indices32[sid] = this._indices[sind + i];
  45478. sid++;
  45479. }
  45480. }
  45481. this.mesh.updateIndices(this._indices32);
  45482. }
  45483. }
  45484. if (this._computeBoundingBox) {
  45485. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45486. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45487. }
  45488. this.afterUpdateParticles(start, end, update);
  45489. return this;
  45490. };
  45491. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45492. this._halfroll = this._roll * 0.5;
  45493. this._halfpitch = this._pitch * 0.5;
  45494. this._halfyaw = this._yaw * 0.5;
  45495. this._sinRoll = Math.sin(this._halfroll);
  45496. this._cosRoll = Math.cos(this._halfroll);
  45497. this._sinPitch = Math.sin(this._halfpitch);
  45498. this._cosPitch = Math.cos(this._halfpitch);
  45499. this._sinYaw = Math.sin(this._halfyaw);
  45500. this._cosYaw = Math.cos(this._halfyaw);
  45501. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45502. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45503. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45504. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45505. };
  45506. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45507. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45508. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45509. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45510. this._rotMatrix.m[3] = 0;
  45511. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45512. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45513. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45514. this._rotMatrix.m[7] = 0;
  45515. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45516. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45517. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45518. this._rotMatrix.m[11] = 0;
  45519. this._rotMatrix.m[12] = 0;
  45520. this._rotMatrix.m[13] = 0;
  45521. this._rotMatrix.m[14] = 0;
  45522. this._rotMatrix.m[15] = 1.0;
  45523. };
  45524. /**
  45525. * Disposes the SPS.
  45526. * Returns nothing.
  45527. */
  45528. SolidParticleSystem.prototype.dispose = function () {
  45529. this.mesh.dispose();
  45530. this.vars = null;
  45531. // drop references to internal big arrays for the GC
  45532. this._positions = null;
  45533. this._indices = null;
  45534. this._normals = null;
  45535. this._uvs = null;
  45536. this._colors = null;
  45537. this._indices32 = null;
  45538. this._positions32 = null;
  45539. this._normals32 = null;
  45540. this._fixedNormal32 = null;
  45541. this._uvs32 = null;
  45542. this._colors32 = null;
  45543. this.pickedParticles = null;
  45544. };
  45545. /**
  45546. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45547. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45548. * Returns the SPS.
  45549. */
  45550. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45551. if (!this._isVisibilityBoxLocked) {
  45552. this.mesh.refreshBoundingInfo();
  45553. }
  45554. return this;
  45555. };
  45556. /**
  45557. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45558. * @param size the size (float) of the visibility box
  45559. * note : this doesn't lock the SPS mesh bounding box.
  45560. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45561. */
  45562. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45563. var vis = size / 2;
  45564. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45565. };
  45566. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45567. // getter and setter
  45568. get: function () {
  45569. return this._alwaysVisible;
  45570. },
  45571. /**
  45572. * Sets the SPS as always visible or not
  45573. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45574. */
  45575. set: function (val) {
  45576. this._alwaysVisible = val;
  45577. this.mesh.alwaysSelectAsActiveMesh = val;
  45578. },
  45579. enumerable: true,
  45580. configurable: true
  45581. });
  45582. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45583. get: function () {
  45584. return this._isVisibilityBoxLocked;
  45585. },
  45586. /**
  45587. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45588. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45589. */
  45590. set: function (val) {
  45591. this._isVisibilityBoxLocked = val;
  45592. var boundingInfo = this.mesh.getBoundingInfo();
  45593. if (boundingInfo) {
  45594. boundingInfo.isLocked = val;
  45595. }
  45596. },
  45597. enumerable: true,
  45598. configurable: true
  45599. });
  45600. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45601. // getters
  45602. get: function () {
  45603. return this._computeParticleRotation;
  45604. },
  45605. // Optimizer setters
  45606. /**
  45607. * Tells to `setParticles()` to compute the particle rotations or not.
  45608. * Default value : true. The SPS is faster when it's set to false.
  45609. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45610. */
  45611. set: function (val) {
  45612. this._computeParticleRotation = val;
  45613. },
  45614. enumerable: true,
  45615. configurable: true
  45616. });
  45617. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45618. get: function () {
  45619. return this._computeParticleColor;
  45620. },
  45621. /**
  45622. * Tells to `setParticles()` to compute the particle colors or not.
  45623. * Default value : true. The SPS is faster when it's set to false.
  45624. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45625. */
  45626. set: function (val) {
  45627. this._computeParticleColor = val;
  45628. },
  45629. enumerable: true,
  45630. configurable: true
  45631. });
  45632. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45633. get: function () {
  45634. return this._computeParticleTexture;
  45635. },
  45636. /**
  45637. * Tells to `setParticles()` to compute the particle textures or not.
  45638. * Default value : true. The SPS is faster when it's set to false.
  45639. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45640. */
  45641. set: function (val) {
  45642. this._computeParticleTexture = val;
  45643. },
  45644. enumerable: true,
  45645. configurable: true
  45646. });
  45647. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45648. get: function () {
  45649. return this._computeParticleVertex;
  45650. },
  45651. /**
  45652. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45653. * Default value : false. The SPS is faster when it's set to false.
  45654. * Note : the particle custom vertex positions aren't stored values.
  45655. */
  45656. set: function (val) {
  45657. this._computeParticleVertex = val;
  45658. },
  45659. enumerable: true,
  45660. configurable: true
  45661. });
  45662. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45663. get: function () {
  45664. return this._computeBoundingBox;
  45665. },
  45666. /**
  45667. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45668. */
  45669. set: function (val) {
  45670. this._computeBoundingBox = val;
  45671. },
  45672. enumerable: true,
  45673. configurable: true
  45674. });
  45675. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45676. get: function () {
  45677. return this._depthSortParticles;
  45678. },
  45679. /**
  45680. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45681. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45682. * Default : `true`
  45683. */
  45684. set: function (val) {
  45685. this._depthSortParticles = val;
  45686. },
  45687. enumerable: true,
  45688. configurable: true
  45689. });
  45690. // =======================================================================
  45691. // Particle behavior logic
  45692. // these following methods may be overwritten by the user to fit his needs
  45693. /**
  45694. * This function does nothing. It may be overwritten to set all the particle first values.
  45695. * The SPS doesn't call this function, you may have to call it by your own.
  45696. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45697. */
  45698. SolidParticleSystem.prototype.initParticles = function () {
  45699. };
  45700. /**
  45701. * This function does nothing. It may be overwritten to recycle a particle.
  45702. * The SPS doesn't call this function, you may have to call it by your own.
  45703. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45704. */
  45705. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45706. return particle;
  45707. };
  45708. /**
  45709. * Updates a particle : this function should be overwritten by the user.
  45710. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45711. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45712. * ex : just set a particle position or velocity and recycle conditions
  45713. */
  45714. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45715. return particle;
  45716. };
  45717. /**
  45718. * Updates a vertex of a particle : it can be overwritten by the user.
  45719. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45720. * @param particle the current particle
  45721. * @param vertex the current index of the current particle
  45722. * @param pt the index of the current vertex in the particle shape
  45723. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45724. * ex : just set a vertex particle position
  45725. */
  45726. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45727. return vertex;
  45728. };
  45729. /**
  45730. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45731. * This does nothing and may be overwritten by the user.
  45732. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45733. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45734. * @param update the boolean update value actually passed to setParticles()
  45735. */
  45736. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45737. };
  45738. /**
  45739. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45740. * This will be passed three parameters.
  45741. * This does nothing and may be overwritten by the user.
  45742. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45743. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45744. * @param update the boolean update value actually passed to setParticles()
  45745. */
  45746. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45747. };
  45748. return SolidParticleSystem;
  45749. }());
  45750. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45751. })(BABYLON || (BABYLON = {}));
  45752. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45753. var BABYLON;
  45754. (function (BABYLON) {
  45755. var GroundMesh = /** @class */ (function (_super) {
  45756. __extends(GroundMesh, _super);
  45757. function GroundMesh(name, scene) {
  45758. var _this = _super.call(this, name, scene) || this;
  45759. _this.generateOctree = false;
  45760. return _this;
  45761. }
  45762. GroundMesh.prototype.getClassName = function () {
  45763. return "GroundMesh";
  45764. };
  45765. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45766. get: function () {
  45767. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45768. },
  45769. enumerable: true,
  45770. configurable: true
  45771. });
  45772. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45773. get: function () {
  45774. return this._subdivisionsX;
  45775. },
  45776. enumerable: true,
  45777. configurable: true
  45778. });
  45779. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45780. get: function () {
  45781. return this._subdivisionsY;
  45782. },
  45783. enumerable: true,
  45784. configurable: true
  45785. });
  45786. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45787. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45788. this._subdivisionsX = chunksCount;
  45789. this._subdivisionsY = chunksCount;
  45790. this.subdivide(chunksCount);
  45791. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45792. };
  45793. /**
  45794. * Returns a height (y) value in the Worl system :
  45795. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45796. * Returns the ground y position if (x, z) are outside the ground surface.
  45797. */
  45798. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45799. var world = this.getWorldMatrix();
  45800. var invMat = BABYLON.Tmp.Matrix[5];
  45801. world.invertToRef(invMat);
  45802. var tmpVect = BABYLON.Tmp.Vector3[8];
  45803. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45804. x = tmpVect.x;
  45805. z = tmpVect.z;
  45806. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45807. return this.position.y;
  45808. }
  45809. if (!this._heightQuads || this._heightQuads.length == 0) {
  45810. this._initHeightQuads();
  45811. this._computeHeightQuads();
  45812. }
  45813. var facet = this._getFacetAt(x, z);
  45814. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45815. // return y in the World system
  45816. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45817. return tmpVect.y;
  45818. };
  45819. /**
  45820. * Returns a normalized vector (Vector3) orthogonal to the ground
  45821. * at the ground coordinates (x, z) expressed in the World system.
  45822. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45823. */
  45824. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45825. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45826. this.getNormalAtCoordinatesToRef(x, z, normal);
  45827. return normal;
  45828. };
  45829. /**
  45830. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45831. * at the ground coordinates (x, z) expressed in the World system.
  45832. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45833. * Returns the GroundMesh.
  45834. */
  45835. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45836. var world = this.getWorldMatrix();
  45837. var tmpMat = BABYLON.Tmp.Matrix[5];
  45838. world.invertToRef(tmpMat);
  45839. var tmpVect = BABYLON.Tmp.Vector3[8];
  45840. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45841. x = tmpVect.x;
  45842. z = tmpVect.z;
  45843. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45844. return this;
  45845. }
  45846. if (!this._heightQuads || this._heightQuads.length == 0) {
  45847. this._initHeightQuads();
  45848. this._computeHeightQuads();
  45849. }
  45850. var facet = this._getFacetAt(x, z);
  45851. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45852. return this;
  45853. };
  45854. /**
  45855. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45856. * if the ground has been updated.
  45857. * This can be used in the render loop.
  45858. * Returns the GroundMesh.
  45859. */
  45860. GroundMesh.prototype.updateCoordinateHeights = function () {
  45861. if (!this._heightQuads || this._heightQuads.length == 0) {
  45862. this._initHeightQuads();
  45863. }
  45864. this._computeHeightQuads();
  45865. return this;
  45866. };
  45867. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45868. GroundMesh.prototype._getFacetAt = function (x, z) {
  45869. // retrieve col and row from x, z coordinates in the ground local system
  45870. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45871. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45872. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45873. var facet;
  45874. if (z < quad.slope.x * x + quad.slope.y) {
  45875. facet = quad.facet1;
  45876. }
  45877. else {
  45878. facet = quad.facet2;
  45879. }
  45880. return facet;
  45881. };
  45882. // Creates and populates the heightMap array with "facet" elements :
  45883. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45884. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45885. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45886. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45887. // Returns the GroundMesh.
  45888. GroundMesh.prototype._initHeightQuads = function () {
  45889. var subdivisionsX = this._subdivisionsX;
  45890. var subdivisionsY = this._subdivisionsY;
  45891. this._heightQuads = new Array();
  45892. for (var row = 0; row < subdivisionsY; row++) {
  45893. for (var col = 0; col < subdivisionsX; col++) {
  45894. 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) };
  45895. this._heightQuads[row * subdivisionsX + col] = quad;
  45896. }
  45897. }
  45898. return this;
  45899. };
  45900. // Compute each quad element values and update the the heightMap array :
  45901. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45902. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45903. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45904. // Returns the GroundMesh.
  45905. GroundMesh.prototype._computeHeightQuads = function () {
  45906. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45907. if (!positions) {
  45908. return this;
  45909. }
  45910. var v1 = BABYLON.Tmp.Vector3[3];
  45911. var v2 = BABYLON.Tmp.Vector3[2];
  45912. var v3 = BABYLON.Tmp.Vector3[1];
  45913. var v4 = BABYLON.Tmp.Vector3[0];
  45914. var v1v2 = BABYLON.Tmp.Vector3[4];
  45915. var v1v3 = BABYLON.Tmp.Vector3[5];
  45916. var v1v4 = BABYLON.Tmp.Vector3[6];
  45917. var norm1 = BABYLON.Tmp.Vector3[7];
  45918. var norm2 = BABYLON.Tmp.Vector3[8];
  45919. var i = 0;
  45920. var j = 0;
  45921. var k = 0;
  45922. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45923. var h = 0;
  45924. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45925. var d2 = 0;
  45926. var subdivisionsX = this._subdivisionsX;
  45927. var subdivisionsY = this._subdivisionsY;
  45928. for (var row = 0; row < subdivisionsY; row++) {
  45929. for (var col = 0; col < subdivisionsX; col++) {
  45930. i = col * 3;
  45931. j = row * (subdivisionsX + 1) * 3;
  45932. k = (row + 1) * (subdivisionsX + 1) * 3;
  45933. v1.x = positions[j + i];
  45934. v1.y = positions[j + i + 1];
  45935. v1.z = positions[j + i + 2];
  45936. v2.x = positions[j + i + 3];
  45937. v2.y = positions[j + i + 4];
  45938. v2.z = positions[j + i + 5];
  45939. v3.x = positions[k + i];
  45940. v3.y = positions[k + i + 1];
  45941. v3.z = positions[k + i + 2];
  45942. v4.x = positions[k + i + 3];
  45943. v4.y = positions[k + i + 4];
  45944. v4.z = positions[k + i + 5];
  45945. // 2D slope V1V4
  45946. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45947. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45948. // facet equations :
  45949. // we compute each facet normal vector
  45950. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45951. // we compute the value d by applying the equation to v1 which belongs to the plane
  45952. // then we store the facet equation in a Vector4
  45953. v2.subtractToRef(v1, v1v2);
  45954. v3.subtractToRef(v1, v1v3);
  45955. v4.subtractToRef(v1, v1v4);
  45956. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45957. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45958. norm1.normalize();
  45959. norm2.normalize();
  45960. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45961. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45962. var quad = this._heightQuads[row * subdivisionsX + col];
  45963. quad.slope.copyFromFloats(cd, h);
  45964. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45965. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45966. }
  45967. }
  45968. return this;
  45969. };
  45970. GroundMesh.prototype.serialize = function (serializationObject) {
  45971. _super.prototype.serialize.call(this, serializationObject);
  45972. serializationObject.subdivisionsX = this._subdivisionsX;
  45973. serializationObject.subdivisionsY = this._subdivisionsY;
  45974. serializationObject.minX = this._minX;
  45975. serializationObject.maxX = this._maxX;
  45976. serializationObject.minZ = this._minZ;
  45977. serializationObject.maxZ = this._maxZ;
  45978. serializationObject.width = this._width;
  45979. serializationObject.height = this._height;
  45980. };
  45981. GroundMesh.Parse = function (parsedMesh, scene) {
  45982. var result = new GroundMesh(parsedMesh.name, scene);
  45983. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45984. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45985. result._minX = parsedMesh.minX;
  45986. result._maxX = parsedMesh.maxX;
  45987. result._minZ = parsedMesh.minZ;
  45988. result._maxZ = parsedMesh.maxZ;
  45989. result._width = parsedMesh.width;
  45990. result._height = parsedMesh.height;
  45991. return result;
  45992. };
  45993. return GroundMesh;
  45994. }(BABYLON.Mesh));
  45995. BABYLON.GroundMesh = GroundMesh;
  45996. })(BABYLON || (BABYLON = {}));
  45997. //# sourceMappingURL=babylon.groundMesh.js.map
  45998. var BABYLON;
  45999. (function (BABYLON) {
  46000. /**
  46001. * Creates an instance based on a source mesh.
  46002. */
  46003. var InstancedMesh = /** @class */ (function (_super) {
  46004. __extends(InstancedMesh, _super);
  46005. function InstancedMesh(name, source) {
  46006. var _this = _super.call(this, name, source.getScene()) || this;
  46007. source.instances.push(_this);
  46008. _this._sourceMesh = source;
  46009. _this.position.copyFrom(source.position);
  46010. _this.rotation.copyFrom(source.rotation);
  46011. _this.scaling.copyFrom(source.scaling);
  46012. if (source.rotationQuaternion) {
  46013. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46014. }
  46015. _this.infiniteDistance = source.infiniteDistance;
  46016. _this.setPivotMatrix(source.getPivotMatrix());
  46017. _this.refreshBoundingInfo();
  46018. _this._syncSubMeshes();
  46019. return _this;
  46020. }
  46021. /**
  46022. * Returns the string "InstancedMesh".
  46023. */
  46024. InstancedMesh.prototype.getClassName = function () {
  46025. return "InstancedMesh";
  46026. };
  46027. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46028. // Methods
  46029. get: function () {
  46030. return this._sourceMesh.receiveShadows;
  46031. },
  46032. enumerable: true,
  46033. configurable: true
  46034. });
  46035. Object.defineProperty(InstancedMesh.prototype, "material", {
  46036. get: function () {
  46037. return this._sourceMesh.material;
  46038. },
  46039. enumerable: true,
  46040. configurable: true
  46041. });
  46042. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46043. get: function () {
  46044. return this._sourceMesh.visibility;
  46045. },
  46046. enumerable: true,
  46047. configurable: true
  46048. });
  46049. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46050. get: function () {
  46051. return this._sourceMesh.skeleton;
  46052. },
  46053. enumerable: true,
  46054. configurable: true
  46055. });
  46056. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46057. get: function () {
  46058. return this._sourceMesh.renderingGroupId;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. /**
  46064. * Returns the total number of vertices (integer).
  46065. */
  46066. InstancedMesh.prototype.getTotalVertices = function () {
  46067. return this._sourceMesh.getTotalVertices();
  46068. };
  46069. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46070. get: function () {
  46071. return this._sourceMesh;
  46072. },
  46073. enumerable: true,
  46074. configurable: true
  46075. });
  46076. /**
  46077. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46078. */
  46079. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46080. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46081. };
  46082. /**
  46083. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46084. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46085. * The `data` are either a numeric array either a Float32Array.
  46086. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46087. * 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).
  46088. * Note that a new underlying VertexBuffer object is created each call.
  46089. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46090. *
  46091. * Possible `kind` values :
  46092. * - BABYLON.VertexBuffer.PositionKind
  46093. * - BABYLON.VertexBuffer.UVKind
  46094. * - BABYLON.VertexBuffer.UV2Kind
  46095. * - BABYLON.VertexBuffer.UV3Kind
  46096. * - BABYLON.VertexBuffer.UV4Kind
  46097. * - BABYLON.VertexBuffer.UV5Kind
  46098. * - BABYLON.VertexBuffer.UV6Kind
  46099. * - BABYLON.VertexBuffer.ColorKind
  46100. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46101. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46102. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46103. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46104. *
  46105. * Returns the Mesh.
  46106. */
  46107. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46108. if (this.sourceMesh) {
  46109. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46110. }
  46111. return this.sourceMesh;
  46112. };
  46113. /**
  46114. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46115. * If the mesh has no geometry, it is simply returned as it is.
  46116. * The `data` are either a numeric array either a Float32Array.
  46117. * No new underlying VertexBuffer object is created.
  46118. * 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.
  46119. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46120. *
  46121. * Possible `kind` values :
  46122. * - BABYLON.VertexBuffer.PositionKind
  46123. * - BABYLON.VertexBuffer.UVKind
  46124. * - BABYLON.VertexBuffer.UV2Kind
  46125. * - BABYLON.VertexBuffer.UV3Kind
  46126. * - BABYLON.VertexBuffer.UV4Kind
  46127. * - BABYLON.VertexBuffer.UV5Kind
  46128. * - BABYLON.VertexBuffer.UV6Kind
  46129. * - BABYLON.VertexBuffer.ColorKind
  46130. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46131. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46132. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46133. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46134. *
  46135. * Returns the Mesh.
  46136. */
  46137. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46138. if (this.sourceMesh) {
  46139. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46140. }
  46141. return this.sourceMesh;
  46142. };
  46143. /**
  46144. * Sets the mesh indices.
  46145. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46146. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46147. * This method creates a new index buffer each call.
  46148. * Returns the Mesh.
  46149. */
  46150. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46151. if (totalVertices === void 0) { totalVertices = null; }
  46152. if (this.sourceMesh) {
  46153. this.sourceMesh.setIndices(indices, totalVertices);
  46154. }
  46155. return this.sourceMesh;
  46156. };
  46157. /**
  46158. * Boolean : True if the mesh owns the requested kind of data.
  46159. */
  46160. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46161. return this._sourceMesh.isVerticesDataPresent(kind);
  46162. };
  46163. /**
  46164. * Returns an array of indices (IndicesArray).
  46165. */
  46166. InstancedMesh.prototype.getIndices = function () {
  46167. return this._sourceMesh.getIndices();
  46168. };
  46169. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46170. get: function () {
  46171. return this._sourceMesh._positions;
  46172. },
  46173. enumerable: true,
  46174. configurable: true
  46175. });
  46176. /**
  46177. * Sets a new updated BoundingInfo to the mesh.
  46178. * Returns the mesh.
  46179. */
  46180. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46181. var meshBB = this._sourceMesh.getBoundingInfo();
  46182. if (meshBB) {
  46183. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46184. }
  46185. this._updateBoundingInfo();
  46186. return this;
  46187. };
  46188. InstancedMesh.prototype._preActivate = function () {
  46189. if (this._currentLOD) {
  46190. this._currentLOD._preActivate();
  46191. }
  46192. return this;
  46193. };
  46194. InstancedMesh.prototype._activate = function (renderId) {
  46195. if (this._currentLOD) {
  46196. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46197. }
  46198. return this;
  46199. };
  46200. /**
  46201. * Returns the current associated LOD AbstractMesh.
  46202. */
  46203. InstancedMesh.prototype.getLOD = function (camera) {
  46204. if (!camera) {
  46205. return this;
  46206. }
  46207. var boundingInfo = this.getBoundingInfo();
  46208. if (!boundingInfo) {
  46209. return this;
  46210. }
  46211. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46212. if (this._currentLOD === this.sourceMesh) {
  46213. return this;
  46214. }
  46215. return this._currentLOD;
  46216. };
  46217. InstancedMesh.prototype._syncSubMeshes = function () {
  46218. this.releaseSubMeshes();
  46219. if (this._sourceMesh.subMeshes) {
  46220. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46221. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46222. }
  46223. }
  46224. return this;
  46225. };
  46226. InstancedMesh.prototype._generatePointsArray = function () {
  46227. return this._sourceMesh._generatePointsArray();
  46228. };
  46229. /**
  46230. * Creates a new InstancedMesh from the current mesh.
  46231. * - name (string) : the cloned mesh name
  46232. * - newParent (optional Node) : the optional Node to parent the clone to.
  46233. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46234. *
  46235. * Returns the clone.
  46236. */
  46237. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46238. var result = this._sourceMesh.createInstance(name);
  46239. // Deep copy
  46240. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46241. // Bounding info
  46242. this.refreshBoundingInfo();
  46243. // Parent
  46244. if (newParent) {
  46245. result.parent = newParent;
  46246. }
  46247. if (!doNotCloneChildren) {
  46248. // Children
  46249. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46250. var mesh = this.getScene().meshes[index];
  46251. if (mesh.parent === this) {
  46252. mesh.clone(mesh.name, result);
  46253. }
  46254. }
  46255. }
  46256. result.computeWorldMatrix(true);
  46257. return result;
  46258. };
  46259. /**
  46260. * Disposes the InstancedMesh.
  46261. * Returns nothing.
  46262. */
  46263. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46264. // Remove from mesh
  46265. var index = this._sourceMesh.instances.indexOf(this);
  46266. this._sourceMesh.instances.splice(index, 1);
  46267. _super.prototype.dispose.call(this, doNotRecurse);
  46268. };
  46269. return InstancedMesh;
  46270. }(BABYLON.AbstractMesh));
  46271. BABYLON.InstancedMesh = InstancedMesh;
  46272. })(BABYLON || (BABYLON = {}));
  46273. //# sourceMappingURL=babylon.instancedMesh.js.map
  46274. var BABYLON;
  46275. (function (BABYLON) {
  46276. var LinesMesh = /** @class */ (function (_super) {
  46277. __extends(LinesMesh, _super);
  46278. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46279. if (scene === void 0) { scene = null; }
  46280. if (parent === void 0) { parent = null; }
  46281. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46282. _this.useVertexColor = useVertexColor;
  46283. _this.color = new BABYLON.Color3(1, 1, 1);
  46284. _this.alpha = 1;
  46285. if (source) {
  46286. _this.color = source.color.clone();
  46287. _this.alpha = source.alpha;
  46288. _this.useVertexColor = source.useVertexColor;
  46289. }
  46290. _this._intersectionThreshold = 0.1;
  46291. var options = {
  46292. attributes: [BABYLON.VertexBuffer.PositionKind],
  46293. uniforms: ["world", "viewProjection"],
  46294. needAlphaBlending: false,
  46295. };
  46296. if (!useVertexColor) {
  46297. options.uniforms.push("color");
  46298. options.needAlphaBlending = true;
  46299. }
  46300. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46301. return _this;
  46302. }
  46303. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46304. /**
  46305. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46306. * This margin is expressed in world space coordinates, so its value may vary.
  46307. * Default value is 0.1
  46308. * @returns the intersection Threshold value.
  46309. */
  46310. get: function () {
  46311. return this._intersectionThreshold;
  46312. },
  46313. /**
  46314. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46315. * This margin is expressed in world space coordinates, so its value may vary.
  46316. * @param value the new threshold to apply
  46317. */
  46318. set: function (value) {
  46319. if (this._intersectionThreshold === value) {
  46320. return;
  46321. }
  46322. this._intersectionThreshold = value;
  46323. if (this.geometry) {
  46324. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46325. }
  46326. },
  46327. enumerable: true,
  46328. configurable: true
  46329. });
  46330. /**
  46331. * Returns the string "LineMesh"
  46332. */
  46333. LinesMesh.prototype.getClassName = function () {
  46334. return "LinesMesh";
  46335. };
  46336. Object.defineProperty(LinesMesh.prototype, "material", {
  46337. get: function () {
  46338. return this._colorShader;
  46339. },
  46340. set: function (value) {
  46341. // Do nothing
  46342. },
  46343. enumerable: true,
  46344. configurable: true
  46345. });
  46346. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46347. get: function () {
  46348. return false;
  46349. },
  46350. enumerable: true,
  46351. configurable: true
  46352. });
  46353. LinesMesh.prototype.createInstance = function (name) {
  46354. throw new Error("LinesMeshes do not support createInstance.");
  46355. };
  46356. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46357. if (!this._geometry) {
  46358. return this;
  46359. }
  46360. // VBOs
  46361. this._geometry._bind(this._colorShader.getEffect());
  46362. // Color
  46363. if (!this.useVertexColor) {
  46364. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46365. }
  46366. return this;
  46367. };
  46368. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46369. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46370. return this;
  46371. }
  46372. var engine = this.getScene().getEngine();
  46373. // Draw order
  46374. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46375. return this;
  46376. };
  46377. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46378. this._colorShader.dispose();
  46379. _super.prototype.dispose.call(this, doNotRecurse);
  46380. };
  46381. /**
  46382. * Returns a new LineMesh object cloned from the current one.
  46383. */
  46384. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46385. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46386. };
  46387. return LinesMesh;
  46388. }(BABYLON.Mesh));
  46389. BABYLON.LinesMesh = LinesMesh;
  46390. })(BABYLON || (BABYLON = {}));
  46391. //# sourceMappingURL=babylon.linesMesh.js.map
  46392. var BABYLON;
  46393. (function (BABYLON) {
  46394. var ShaderMaterial = /** @class */ (function (_super) {
  46395. __extends(ShaderMaterial, _super);
  46396. function ShaderMaterial(name, scene, shaderPath, options) {
  46397. var _this = _super.call(this, name, scene) || this;
  46398. _this._textures = {};
  46399. _this._textureArrays = {};
  46400. _this._floats = {};
  46401. _this._floatsArrays = {};
  46402. _this._colors3 = {};
  46403. _this._colors3Arrays = {};
  46404. _this._colors4 = {};
  46405. _this._vectors2 = {};
  46406. _this._vectors3 = {};
  46407. _this._vectors4 = {};
  46408. _this._matrices = {};
  46409. _this._matrices3x3 = {};
  46410. _this._matrices2x2 = {};
  46411. _this._vectors3Arrays = {};
  46412. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46413. _this._shaderPath = shaderPath;
  46414. options.needAlphaBlending = options.needAlphaBlending || false;
  46415. options.needAlphaTesting = options.needAlphaTesting || false;
  46416. options.attributes = options.attributes || ["position", "normal", "uv"];
  46417. options.uniforms = options.uniforms || ["worldViewProjection"];
  46418. options.uniformBuffers = options.uniformBuffers || [];
  46419. options.samplers = options.samplers || [];
  46420. options.defines = options.defines || [];
  46421. _this._options = options;
  46422. return _this;
  46423. }
  46424. ShaderMaterial.prototype.getClassName = function () {
  46425. return "ShaderMaterial";
  46426. };
  46427. ShaderMaterial.prototype.needAlphaBlending = function () {
  46428. return this._options.needAlphaBlending;
  46429. };
  46430. ShaderMaterial.prototype.needAlphaTesting = function () {
  46431. return this._options.needAlphaTesting;
  46432. };
  46433. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46434. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46435. this._options.uniforms.push(uniformName);
  46436. }
  46437. };
  46438. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46439. if (this._options.samplers.indexOf(name) === -1) {
  46440. this._options.samplers.push(name);
  46441. }
  46442. this._textures[name] = texture;
  46443. return this;
  46444. };
  46445. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46446. if (this._options.samplers.indexOf(name) === -1) {
  46447. this._options.samplers.push(name);
  46448. }
  46449. this._checkUniform(name);
  46450. this._textureArrays[name] = textures;
  46451. return this;
  46452. };
  46453. ShaderMaterial.prototype.setFloat = function (name, value) {
  46454. this._checkUniform(name);
  46455. this._floats[name] = value;
  46456. return this;
  46457. };
  46458. ShaderMaterial.prototype.setFloats = function (name, value) {
  46459. this._checkUniform(name);
  46460. this._floatsArrays[name] = value;
  46461. return this;
  46462. };
  46463. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46464. this._checkUniform(name);
  46465. this._colors3[name] = value;
  46466. return this;
  46467. };
  46468. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46469. this._checkUniform(name);
  46470. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46471. color.toArray(arr, arr.length);
  46472. return arr;
  46473. }, []);
  46474. return this;
  46475. };
  46476. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46477. this._checkUniform(name);
  46478. this._colors4[name] = value;
  46479. return this;
  46480. };
  46481. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46482. this._checkUniform(name);
  46483. this._vectors2[name] = value;
  46484. return this;
  46485. };
  46486. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46487. this._checkUniform(name);
  46488. this._vectors3[name] = value;
  46489. return this;
  46490. };
  46491. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46492. this._checkUniform(name);
  46493. this._vectors4[name] = value;
  46494. return this;
  46495. };
  46496. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46497. this._checkUniform(name);
  46498. this._matrices[name] = value;
  46499. return this;
  46500. };
  46501. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46502. this._checkUniform(name);
  46503. this._matrices3x3[name] = value;
  46504. return this;
  46505. };
  46506. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46507. this._checkUniform(name);
  46508. this._matrices2x2[name] = value;
  46509. return this;
  46510. };
  46511. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46512. this._checkUniform(name);
  46513. this._vectors3Arrays[name] = value;
  46514. return this;
  46515. };
  46516. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46517. if (!mesh) {
  46518. return true;
  46519. }
  46520. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46521. return false;
  46522. }
  46523. return false;
  46524. };
  46525. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46526. var scene = this.getScene();
  46527. var engine = scene.getEngine();
  46528. if (!this.checkReadyOnEveryCall) {
  46529. if (this._renderId === scene.getRenderId()) {
  46530. if (this._checkCache(scene, mesh, useInstances)) {
  46531. return true;
  46532. }
  46533. }
  46534. }
  46535. // Instances
  46536. var defines = [];
  46537. var attribs = [];
  46538. var fallbacks = new BABYLON.EffectFallbacks();
  46539. if (useInstances) {
  46540. defines.push("#define INSTANCES");
  46541. }
  46542. for (var index = 0; index < this._options.defines.length; index++) {
  46543. defines.push(this._options.defines[index]);
  46544. }
  46545. for (var index = 0; index < this._options.attributes.length; index++) {
  46546. attribs.push(this._options.attributes[index]);
  46547. }
  46548. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46549. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46550. defines.push("#define VERTEXCOLOR");
  46551. }
  46552. // Bones
  46553. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46554. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46555. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46556. if (mesh.numBoneInfluencers > 4) {
  46557. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46558. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46559. }
  46560. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46561. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46562. fallbacks.addCPUSkinningFallback(0, mesh);
  46563. if (this._options.uniforms.indexOf("mBones") === -1) {
  46564. this._options.uniforms.push("mBones");
  46565. }
  46566. }
  46567. else {
  46568. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46569. }
  46570. // Textures
  46571. for (var name in this._textures) {
  46572. if (!this._textures[name].isReady()) {
  46573. return false;
  46574. }
  46575. }
  46576. // Alpha test
  46577. if (engine.getAlphaTesting()) {
  46578. defines.push("#define ALPHATEST");
  46579. }
  46580. var previousEffect = this._effect;
  46581. var join = defines.join("\n");
  46582. this._effect = engine.createEffect(this._shaderPath, {
  46583. attributes: attribs,
  46584. uniformsNames: this._options.uniforms,
  46585. uniformBuffersNames: this._options.uniformBuffers,
  46586. samplers: this._options.samplers,
  46587. defines: join,
  46588. fallbacks: fallbacks,
  46589. onCompiled: this.onCompiled,
  46590. onError: this.onError
  46591. }, engine);
  46592. if (!this._effect.isReady()) {
  46593. return false;
  46594. }
  46595. if (previousEffect !== this._effect) {
  46596. scene.resetCachedMaterial();
  46597. }
  46598. this._renderId = scene.getRenderId();
  46599. return true;
  46600. };
  46601. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46602. var scene = this.getScene();
  46603. if (!this._effect) {
  46604. return;
  46605. }
  46606. if (this._options.uniforms.indexOf("world") !== -1) {
  46607. this._effect.setMatrix("world", world);
  46608. }
  46609. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46610. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46611. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46612. }
  46613. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46614. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46615. }
  46616. };
  46617. ShaderMaterial.prototype.bind = function (world, mesh) {
  46618. // Std values
  46619. this.bindOnlyWorldMatrix(world);
  46620. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46621. if (this._options.uniforms.indexOf("view") !== -1) {
  46622. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46623. }
  46624. if (this._options.uniforms.indexOf("projection") !== -1) {
  46625. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46626. }
  46627. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46628. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46629. }
  46630. // Bones
  46631. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46632. var name;
  46633. // Texture
  46634. for (name in this._textures) {
  46635. this._effect.setTexture(name, this._textures[name]);
  46636. }
  46637. // Texture arrays
  46638. for (name in this._textureArrays) {
  46639. this._effect.setTextureArray(name, this._textureArrays[name]);
  46640. }
  46641. // Float
  46642. for (name in this._floats) {
  46643. this._effect.setFloat(name, this._floats[name]);
  46644. }
  46645. // Float s
  46646. for (name in this._floatsArrays) {
  46647. this._effect.setArray(name, this._floatsArrays[name]);
  46648. }
  46649. // Color3
  46650. for (name in this._colors3) {
  46651. this._effect.setColor3(name, this._colors3[name]);
  46652. }
  46653. for (name in this._colors3Arrays) {
  46654. this._effect.setArray3(name, this._colors3Arrays[name]);
  46655. }
  46656. // Color4
  46657. for (name in this._colors4) {
  46658. var color = this._colors4[name];
  46659. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46660. }
  46661. // Vector2
  46662. for (name in this._vectors2) {
  46663. this._effect.setVector2(name, this._vectors2[name]);
  46664. }
  46665. // Vector3
  46666. for (name in this._vectors3) {
  46667. this._effect.setVector3(name, this._vectors3[name]);
  46668. }
  46669. // Vector4
  46670. for (name in this._vectors4) {
  46671. this._effect.setVector4(name, this._vectors4[name]);
  46672. }
  46673. // Matrix
  46674. for (name in this._matrices) {
  46675. this._effect.setMatrix(name, this._matrices[name]);
  46676. }
  46677. // Matrix 3x3
  46678. for (name in this._matrices3x3) {
  46679. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46680. }
  46681. // Matrix 2x2
  46682. for (name in this._matrices2x2) {
  46683. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46684. }
  46685. // Vector3Array
  46686. for (name in this._vectors3Arrays) {
  46687. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46688. }
  46689. }
  46690. this._afterBind(mesh);
  46691. };
  46692. ShaderMaterial.prototype.getActiveTextures = function () {
  46693. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46694. for (var name in this._textures) {
  46695. activeTextures.push(this._textures[name]);
  46696. }
  46697. for (var name in this._textureArrays) {
  46698. var array = this._textureArrays[name];
  46699. for (var index = 0; index < array.length; index++) {
  46700. activeTextures.push(array[index]);
  46701. }
  46702. }
  46703. return activeTextures;
  46704. };
  46705. ShaderMaterial.prototype.hasTexture = function (texture) {
  46706. if (_super.prototype.hasTexture.call(this, texture)) {
  46707. return true;
  46708. }
  46709. for (var name in this._textures) {
  46710. if (this._textures[name] === texture) {
  46711. return true;
  46712. }
  46713. }
  46714. for (var name in this._textureArrays) {
  46715. var array = this._textureArrays[name];
  46716. for (var index = 0; index < array.length; index++) {
  46717. if (array[index] === texture) {
  46718. return true;
  46719. }
  46720. }
  46721. }
  46722. return false;
  46723. };
  46724. ShaderMaterial.prototype.clone = function (name) {
  46725. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46726. return newShaderMaterial;
  46727. };
  46728. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46729. if (forceDisposeTextures) {
  46730. var name;
  46731. for (name in this._textures) {
  46732. this._textures[name].dispose();
  46733. }
  46734. for (name in this._textureArrays) {
  46735. var array = this._textureArrays[name];
  46736. for (var index = 0; index < array.length; index++) {
  46737. array[index].dispose();
  46738. }
  46739. }
  46740. }
  46741. this._textures = {};
  46742. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46743. };
  46744. ShaderMaterial.prototype.serialize = function () {
  46745. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46746. serializationObject.customType = "BABYLON.ShaderMaterial";
  46747. serializationObject.options = this._options;
  46748. serializationObject.shaderPath = this._shaderPath;
  46749. var name;
  46750. // Texture
  46751. serializationObject.textures = {};
  46752. for (name in this._textures) {
  46753. serializationObject.textures[name] = this._textures[name].serialize();
  46754. }
  46755. // Texture arrays
  46756. serializationObject.textureArrays = {};
  46757. for (name in this._textureArrays) {
  46758. serializationObject.textureArrays[name] = [];
  46759. var array = this._textureArrays[name];
  46760. for (var index = 0; index < array.length; index++) {
  46761. serializationObject.textureArrays[name].push(array[index].serialize());
  46762. }
  46763. }
  46764. // Float
  46765. serializationObject.floats = {};
  46766. for (name in this._floats) {
  46767. serializationObject.floats[name] = this._floats[name];
  46768. }
  46769. // Float s
  46770. serializationObject.FloatArrays = {};
  46771. for (name in this._floatsArrays) {
  46772. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46773. }
  46774. // Color3
  46775. serializationObject.colors3 = {};
  46776. for (name in this._colors3) {
  46777. serializationObject.colors3[name] = this._colors3[name].asArray();
  46778. }
  46779. // Color3 array
  46780. serializationObject.colors3Arrays = {};
  46781. for (name in this._colors3Arrays) {
  46782. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46783. }
  46784. // Color4
  46785. serializationObject.colors4 = {};
  46786. for (name in this._colors4) {
  46787. serializationObject.colors4[name] = this._colors4[name].asArray();
  46788. }
  46789. // Vector2
  46790. serializationObject.vectors2 = {};
  46791. for (name in this._vectors2) {
  46792. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46793. }
  46794. // Vector3
  46795. serializationObject.vectors3 = {};
  46796. for (name in this._vectors3) {
  46797. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46798. }
  46799. // Vector4
  46800. serializationObject.vectors4 = {};
  46801. for (name in this._vectors4) {
  46802. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46803. }
  46804. // Matrix
  46805. serializationObject.matrices = {};
  46806. for (name in this._matrices) {
  46807. serializationObject.matrices[name] = this._matrices[name].asArray();
  46808. }
  46809. // Matrix 3x3
  46810. serializationObject.matrices3x3 = {};
  46811. for (name in this._matrices3x3) {
  46812. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46813. }
  46814. // Matrix 2x2
  46815. serializationObject.matrices2x2 = {};
  46816. for (name in this._matrices2x2) {
  46817. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46818. }
  46819. // Vector3Array
  46820. serializationObject.vectors3Arrays = {};
  46821. for (name in this._vectors3Arrays) {
  46822. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46823. }
  46824. return serializationObject;
  46825. };
  46826. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46827. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46828. var name;
  46829. // Texture
  46830. for (name in source.textures) {
  46831. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46832. }
  46833. // Texture arrays
  46834. for (name in source.textureArrays) {
  46835. var array = source.textureArrays[name];
  46836. var textureArray = new Array();
  46837. for (var index = 0; index < array.length; index++) {
  46838. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46839. }
  46840. material.setTextureArray(name, textureArray);
  46841. }
  46842. // Float
  46843. for (name in source.floats) {
  46844. material.setFloat(name, source.floats[name]);
  46845. }
  46846. // Float s
  46847. for (name in source.floatsArrays) {
  46848. material.setFloats(name, source.floatsArrays[name]);
  46849. }
  46850. // Color3
  46851. for (name in source.colors3) {
  46852. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46853. }
  46854. // Color3 arrays
  46855. for (name in source.colors3Arrays) {
  46856. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46857. if (i % 3 === 0) {
  46858. arr.push([num]);
  46859. }
  46860. else {
  46861. arr[arr.length - 1].push(num);
  46862. }
  46863. return arr;
  46864. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46865. material.setColor3Array(name, colors);
  46866. }
  46867. // Color4
  46868. for (name in source.colors4) {
  46869. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46870. }
  46871. // Vector2
  46872. for (name in source.vectors2) {
  46873. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46874. }
  46875. // Vector3
  46876. for (name in source.vectors3) {
  46877. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46878. }
  46879. // Vector4
  46880. for (name in source.vectors4) {
  46881. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46882. }
  46883. // Matrix
  46884. for (name in source.matrices) {
  46885. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46886. }
  46887. // Matrix 3x3
  46888. for (name in source.matrices3x3) {
  46889. material.setMatrix3x3(name, source.matrices3x3[name]);
  46890. }
  46891. // Matrix 2x2
  46892. for (name in source.matrices2x2) {
  46893. material.setMatrix2x2(name, source.matrices2x2[name]);
  46894. }
  46895. // Vector3Array
  46896. for (name in source.vectors3Arrays) {
  46897. material.setArray3(name, source.vectors3Arrays[name]);
  46898. }
  46899. return material;
  46900. };
  46901. return ShaderMaterial;
  46902. }(BABYLON.Material));
  46903. BABYLON.ShaderMaterial = ShaderMaterial;
  46904. })(BABYLON || (BABYLON = {}));
  46905. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46906. var BABYLON;
  46907. (function (BABYLON) {
  46908. var MeshBuilder = /** @class */ (function () {
  46909. function MeshBuilder() {
  46910. }
  46911. MeshBuilder.updateSideOrientation = function (orientation) {
  46912. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46913. return BABYLON.Mesh.DOUBLESIDE;
  46914. }
  46915. if (orientation === undefined || orientation === null) {
  46916. return BABYLON.Mesh.FRONTSIDE;
  46917. }
  46918. return orientation;
  46919. };
  46920. /**
  46921. * Creates a box mesh.
  46922. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46923. * The parameter `size` sets the size (float) of each box side (default 1).
  46924. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46925. * 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).
  46926. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46927. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46928. * 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).
  46929. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46931. */
  46932. MeshBuilder.CreateBox = function (name, options, scene) {
  46933. if (scene === void 0) { scene = null; }
  46934. var box = new BABYLON.Mesh(name, scene);
  46935. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46936. box._originalBuilderSideOrientation = options.sideOrientation;
  46937. var vertexData = BABYLON.VertexData.CreateBox(options);
  46938. vertexData.applyToMesh(box, options.updatable);
  46939. return box;
  46940. };
  46941. /**
  46942. * Creates a sphere mesh.
  46943. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46944. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46945. * 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`).
  46946. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46947. * 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
  46948. * 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).
  46949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46950. * 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).
  46951. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46953. */
  46954. MeshBuilder.CreateSphere = function (name, options, scene) {
  46955. var sphere = new BABYLON.Mesh(name, scene);
  46956. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46957. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46958. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46959. vertexData.applyToMesh(sphere, options.updatable);
  46960. return sphere;
  46961. };
  46962. /**
  46963. * Creates a plane polygonal mesh. By default, this is a disc.
  46964. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46965. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46966. * 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.
  46967. * 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
  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.CreateDisc = function (name, options, scene) {
  46974. if (scene === void 0) { scene = null; }
  46975. var disc = new BABYLON.Mesh(name, scene);
  46976. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46977. disc._originalBuilderSideOrientation = options.sideOrientation;
  46978. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46979. vertexData.applyToMesh(disc, options.updatable);
  46980. return disc;
  46981. };
  46982. /**
  46983. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46984. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46985. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46986. * 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`).
  46987. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46988. * 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.
  46989. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46990. * 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).
  46991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46993. */
  46994. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46995. var sphere = new BABYLON.Mesh(name, scene);
  46996. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46997. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46998. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46999. vertexData.applyToMesh(sphere, options.updatable);
  47000. return sphere;
  47001. };
  47002. ;
  47003. /**
  47004. * Creates a ribbon mesh.
  47005. * 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.
  47006. *
  47007. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47008. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47009. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47010. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47011. * 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.
  47012. * 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.
  47013. * 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
  47014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47015. * 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).
  47016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47017. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47018. * 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.
  47019. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47020. * 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
  47021. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47022. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47024. */
  47025. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47026. if (scene === void 0) { scene = null; }
  47027. var pathArray = options.pathArray;
  47028. var closeArray = options.closeArray;
  47029. var closePath = options.closePath;
  47030. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47031. var instance = options.instance;
  47032. var updatable = options.updatable;
  47033. if (instance) {
  47034. // positionFunction : ribbon case
  47035. // only pathArray and sideOrientation parameters are taken into account for positions update
  47036. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47037. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47038. var positionFunction = function (positions) {
  47039. var minlg = pathArray[0].length;
  47040. var i = 0;
  47041. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47042. for (var si = 1; si <= ns; si++) {
  47043. for (var p = 0; p < pathArray.length; p++) {
  47044. var path = pathArray[p];
  47045. var l = path.length;
  47046. minlg = (minlg < l) ? minlg : l;
  47047. var j = 0;
  47048. while (j < minlg) {
  47049. positions[i] = path[j].x;
  47050. positions[i + 1] = path[j].y;
  47051. positions[i + 2] = path[j].z;
  47052. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47053. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47054. }
  47055. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47056. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47057. }
  47058. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47059. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47060. }
  47061. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47062. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47063. }
  47064. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47065. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47066. }
  47067. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47068. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47069. }
  47070. j++;
  47071. i += 3;
  47072. }
  47073. if (instance._closePath) {
  47074. positions[i] = path[0].x;
  47075. positions[i + 1] = path[0].y;
  47076. positions[i + 2] = path[0].z;
  47077. i += 3;
  47078. }
  47079. }
  47080. }
  47081. };
  47082. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47083. positionFunction(positions);
  47084. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47085. instance._boundingInfo.update(instance._worldMatrix);
  47086. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47087. if (options.colors) {
  47088. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47089. for (var c = 0; c < options.colors.length; c++) {
  47090. colors[c * 4] = options.colors[c].r;
  47091. colors[c * 4 + 1] = options.colors[c].g;
  47092. colors[c * 4 + 2] = options.colors[c].b;
  47093. colors[c * 4 + 3] = options.colors[c].a;
  47094. }
  47095. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47096. }
  47097. if (options.uvs) {
  47098. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47099. for (var i = 0; i < options.uvs.length; i++) {
  47100. uvs[i * 2] = options.uvs[i].x;
  47101. uvs[i * 2 + 1] = options.uvs[i].y;
  47102. }
  47103. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47104. }
  47105. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47106. var indices = instance.getIndices();
  47107. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47108. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47109. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47110. if (instance._closePath) {
  47111. var indexFirst = 0;
  47112. var indexLast = 0;
  47113. for (var p = 0; p < pathArray.length; p++) {
  47114. indexFirst = instance._idx[p] * 3;
  47115. if (p + 1 < pathArray.length) {
  47116. indexLast = (instance._idx[p + 1] - 1) * 3;
  47117. }
  47118. else {
  47119. indexLast = normals.length - 3;
  47120. }
  47121. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47122. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47123. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47124. normals[indexLast] = normals[indexFirst];
  47125. normals[indexLast + 1] = normals[indexFirst + 1];
  47126. normals[indexLast + 2] = normals[indexFirst + 2];
  47127. }
  47128. }
  47129. if (!(instance.areNormalsFrozen)) {
  47130. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47131. }
  47132. }
  47133. return instance;
  47134. }
  47135. else {
  47136. var ribbon = new BABYLON.Mesh(name, scene);
  47137. ribbon._originalBuilderSideOrientation = sideOrientation;
  47138. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47139. if (closePath) {
  47140. ribbon._idx = vertexData._idx;
  47141. }
  47142. ribbon._closePath = closePath;
  47143. ribbon._closeArray = closeArray;
  47144. vertexData.applyToMesh(ribbon, updatable);
  47145. return ribbon;
  47146. }
  47147. };
  47148. /**
  47149. * Creates a cylinder or a cone mesh.
  47150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47151. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47152. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47153. * 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.
  47154. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47155. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47156. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47157. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47158. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47159. * 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).
  47160. * 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
  47161. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47162. * 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
  47163. * 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.
  47164. * If `enclose` is false, a ring surface is one element.
  47165. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47166. * 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
  47167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47168. * 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).
  47169. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47171. */
  47172. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47173. var cylinder = new BABYLON.Mesh(name, scene);
  47174. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47175. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47176. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47177. vertexData.applyToMesh(cylinder, options.updatable);
  47178. return cylinder;
  47179. };
  47180. /**
  47181. * Creates a torus mesh.
  47182. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47183. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47184. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47185. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47186. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47187. * 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).
  47188. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47190. */
  47191. MeshBuilder.CreateTorus = function (name, options, scene) {
  47192. var torus = new BABYLON.Mesh(name, scene);
  47193. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47194. torus._originalBuilderSideOrientation = options.sideOrientation;
  47195. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47196. vertexData.applyToMesh(torus, options.updatable);
  47197. return torus;
  47198. };
  47199. /**
  47200. * Creates a torus knot mesh.
  47201. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47202. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47203. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47204. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47205. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47207. * 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).
  47208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47210. */
  47211. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47212. var torusKnot = new BABYLON.Mesh(name, scene);
  47213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47214. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47215. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47216. vertexData.applyToMesh(torusKnot, options.updatable);
  47217. return torusKnot;
  47218. };
  47219. /**
  47220. * Creates a line system mesh.
  47221. * A line system is a pool of many lines gathered in a single mesh.
  47222. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47223. * 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.
  47224. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47225. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47226. * 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
  47227. * 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
  47228. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47230. */
  47231. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47232. var instance = options.instance;
  47233. var lines = options.lines;
  47234. if (instance) {
  47235. var positionFunction = function (positions) {
  47236. var i = 0;
  47237. for (var l = 0; l < lines.length; l++) {
  47238. var points = lines[l];
  47239. for (var p = 0; p < points.length; p++) {
  47240. positions[i] = points[p].x;
  47241. positions[i + 1] = points[p].y;
  47242. positions[i + 2] = points[p].z;
  47243. i += 3;
  47244. }
  47245. }
  47246. };
  47247. instance.updateMeshPositions(positionFunction, false);
  47248. return instance;
  47249. }
  47250. // line system creation
  47251. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47252. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47253. vertexData.applyToMesh(lineSystem, options.updatable);
  47254. return lineSystem;
  47255. };
  47256. /**
  47257. * Creates a line mesh.
  47258. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47259. * 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.
  47260. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47261. * The parameter `points` is an array successive Vector3.
  47262. * 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
  47263. * When updating an instance, remember that only point positions can change, not the number of points.
  47264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47265. */
  47266. MeshBuilder.CreateLines = function (name, options, scene) {
  47267. if (scene === void 0) { scene = null; }
  47268. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47269. return lines;
  47270. };
  47271. /**
  47272. * Creates a dashed line mesh.
  47273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47274. * 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.
  47275. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47276. * The parameter `points` is an array successive Vector3.
  47277. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47278. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47279. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47280. * 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
  47281. * When updating an instance, remember that only point positions can change, not the number of points.
  47282. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47283. */
  47284. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47285. if (scene === void 0) { scene = null; }
  47286. var points = options.points;
  47287. var instance = options.instance;
  47288. var gapSize = options.gapSize || 1;
  47289. var dashSize = options.dashSize || 3;
  47290. if (instance) {
  47291. var positionFunction = function (positions) {
  47292. var curvect = BABYLON.Vector3.Zero();
  47293. var nbSeg = positions.length / 6;
  47294. var lg = 0;
  47295. var nb = 0;
  47296. var shft = 0;
  47297. var dashshft = 0;
  47298. var curshft = 0;
  47299. var p = 0;
  47300. var i = 0;
  47301. var j = 0;
  47302. for (i = 0; i < points.length - 1; i++) {
  47303. points[i + 1].subtractToRef(points[i], curvect);
  47304. lg += curvect.length();
  47305. }
  47306. shft = lg / nbSeg;
  47307. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47308. for (i = 0; i < points.length - 1; i++) {
  47309. points[i + 1].subtractToRef(points[i], curvect);
  47310. nb = Math.floor(curvect.length() / shft);
  47311. curvect.normalize();
  47312. j = 0;
  47313. while (j < nb && p < positions.length) {
  47314. curshft = shft * j;
  47315. positions[p] = points[i].x + curshft * curvect.x;
  47316. positions[p + 1] = points[i].y + curshft * curvect.y;
  47317. positions[p + 2] = points[i].z + curshft * curvect.z;
  47318. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47319. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47320. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47321. p += 6;
  47322. j++;
  47323. }
  47324. }
  47325. while (p < positions.length) {
  47326. positions[p] = points[i].x;
  47327. positions[p + 1] = points[i].y;
  47328. positions[p + 2] = points[i].z;
  47329. p += 3;
  47330. }
  47331. };
  47332. instance.updateMeshPositions(positionFunction, false);
  47333. return instance;
  47334. }
  47335. // dashed lines creation
  47336. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47337. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47338. vertexData.applyToMesh(dashedLines, options.updatable);
  47339. dashedLines.dashSize = dashSize;
  47340. dashedLines.gapSize = gapSize;
  47341. return dashedLines;
  47342. };
  47343. /**
  47344. * Creates an extruded shape mesh.
  47345. * 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.
  47346. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47347. *
  47348. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47349. * 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
  47350. * extruded along the Z axis.
  47351. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47352. * 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.
  47353. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47354. * 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
  47355. * 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
  47356. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47358. * 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).
  47359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47360. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47362. */
  47363. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47364. if (scene === void 0) { scene = null; }
  47365. var path = options.path;
  47366. var shape = options.shape;
  47367. var scale = options.scale || 1;
  47368. var rotation = options.rotation || 0;
  47369. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47370. var updatable = options.updatable;
  47371. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47372. var instance = options.instance || null;
  47373. var invertUV = options.invertUV || false;
  47374. 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);
  47375. };
  47376. /**
  47377. * Creates an custom extruded shape mesh.
  47378. * 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.
  47379. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47380. *
  47381. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47382. * 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
  47383. * extruded along the Z axis.
  47384. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47385. * 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
  47386. * and the distance of this point from the begining of the path :
  47387. * ```javascript
  47388. * var rotationFunction = function(i, distance) {
  47389. * // do things
  47390. * return rotationValue; }
  47391. * ```
  47392. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47393. * 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
  47394. * and the distance of this point from the begining of the path :
  47395. * ```javascript
  47396. * var scaleFunction = function(i, distance) {
  47397. * // do things
  47398. * return scaleValue;}
  47399. * ```
  47400. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47401. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47402. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47403. * 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
  47404. * 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
  47405. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47407. * 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).
  47408. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47409. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47411. */
  47412. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47413. var path = options.path;
  47414. var shape = options.shape;
  47415. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47416. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47417. var ribbonCloseArray = options.ribbonCloseArray || false;
  47418. var ribbonClosePath = options.ribbonClosePath || false;
  47419. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47420. var updatable = options.updatable;
  47421. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47422. var instance = options.instance;
  47423. var invertUV = options.invertUV || false;
  47424. 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);
  47425. };
  47426. /**
  47427. * Creates lathe mesh.
  47428. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47430. *
  47431. * 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
  47432. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47433. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47434. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47435. * 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.
  47436. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47437. * 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
  47438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47439. * 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).
  47440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47441. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47443. */
  47444. MeshBuilder.CreateLathe = function (name, options, scene) {
  47445. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47446. var closed = (options.closed === undefined) ? true : options.closed;
  47447. var shape = options.shape;
  47448. var radius = options.radius || 1;
  47449. var tessellation = options.tessellation || 64;
  47450. var updatable = options.updatable;
  47451. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47452. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47453. var pi2 = Math.PI * 2;
  47454. var paths = new Array();
  47455. var invertUV = options.invertUV || false;
  47456. var i = 0;
  47457. var p = 0;
  47458. var step = pi2 / tessellation * arc;
  47459. var rotated;
  47460. var path = new Array();
  47461. ;
  47462. for (i = 0; i <= tessellation; i++) {
  47463. var path = [];
  47464. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47465. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47466. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47467. }
  47468. for (p = 0; p < shape.length; p++) {
  47469. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47470. path.push(rotated);
  47471. }
  47472. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47473. 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));
  47474. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47475. }
  47476. paths.push(path);
  47477. }
  47478. // lathe ribbon
  47479. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47480. return lathe;
  47481. };
  47482. /**
  47483. * Creates a plane mesh.
  47484. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47485. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47486. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47487. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47489. * 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).
  47490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreatePlane = function (name, options, scene) {
  47494. var plane = new BABYLON.Mesh(name, scene);
  47495. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47496. plane._originalBuilderSideOrientation = options.sideOrientation;
  47497. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47498. vertexData.applyToMesh(plane, options.updatable);
  47499. if (options.sourcePlane) {
  47500. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47501. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47502. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47503. plane.rotate(vectorProduct, product);
  47504. }
  47505. return plane;
  47506. };
  47507. /**
  47508. * Creates a ground mesh.
  47509. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47510. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47511. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47513. */
  47514. MeshBuilder.CreateGround = function (name, options, scene) {
  47515. var ground = new BABYLON.GroundMesh(name, scene);
  47516. ground._setReady(false);
  47517. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47518. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47519. ground._width = options.width || 1;
  47520. ground._height = options.height || 1;
  47521. ground._maxX = ground._width / 2;
  47522. ground._maxZ = ground._height / 2;
  47523. ground._minX = -ground._maxX;
  47524. ground._minZ = -ground._maxZ;
  47525. var vertexData = BABYLON.VertexData.CreateGround(options);
  47526. vertexData.applyToMesh(ground, options.updatable);
  47527. ground._setReady(true);
  47528. return ground;
  47529. };
  47530. /**
  47531. * Creates a tiled ground mesh.
  47532. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47533. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47534. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47535. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47536. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47537. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47538. * numbers of subdivisions on the ground width and height of each tile.
  47539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47540. */
  47541. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47542. var tiledGround = new BABYLON.Mesh(name, scene);
  47543. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47544. vertexData.applyToMesh(tiledGround, options.updatable);
  47545. return tiledGround;
  47546. };
  47547. /**
  47548. * Creates a ground mesh from a height map.
  47549. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47550. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47551. * The parameter `url` sets the URL of the height map image resource.
  47552. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47553. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47554. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47555. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47556. * 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.
  47557. * 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).
  47558. * This function is passed the newly built mesh :
  47559. * ```javascript
  47560. * function(mesh) { // do things
  47561. * return; }
  47562. * ```
  47563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47564. */
  47565. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47566. var width = options.width || 10.0;
  47567. var height = options.height || 10.0;
  47568. var subdivisions = options.subdivisions || 1 | 0;
  47569. var minHeight = options.minHeight || 0.0;
  47570. var maxHeight = options.maxHeight || 1.0;
  47571. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47572. var updatable = options.updatable;
  47573. var onReady = options.onReady;
  47574. var ground = new BABYLON.GroundMesh(name, scene);
  47575. ground._subdivisionsX = subdivisions;
  47576. ground._subdivisionsY = subdivisions;
  47577. ground._width = width;
  47578. ground._height = height;
  47579. ground._maxX = ground._width / 2.0;
  47580. ground._maxZ = ground._height / 2.0;
  47581. ground._minX = -ground._maxX;
  47582. ground._minZ = -ground._maxZ;
  47583. ground._setReady(false);
  47584. var onload = function (img) {
  47585. // Getting height map data
  47586. var canvas = document.createElement("canvas");
  47587. var context = canvas.getContext("2d");
  47588. if (!context) {
  47589. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47590. }
  47591. var bufferWidth = img.width;
  47592. var bufferHeight = img.height;
  47593. canvas.width = bufferWidth;
  47594. canvas.height = bufferHeight;
  47595. context.drawImage(img, 0, 0);
  47596. // Create VertexData from map data
  47597. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47598. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47599. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47600. width: width, height: height,
  47601. subdivisions: subdivisions,
  47602. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47603. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47604. });
  47605. vertexData.applyToMesh(ground, updatable);
  47606. ground._setReady(true);
  47607. //execute ready callback, if set
  47608. if (onReady) {
  47609. onReady(ground);
  47610. }
  47611. };
  47612. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47613. return ground;
  47614. };
  47615. /**
  47616. * Creates a polygon mesh.
  47617. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47618. * 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.
  47619. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47621. * 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).
  47622. * Remember you can only change the shape positions, not their number when updating a polygon.
  47623. */
  47624. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47625. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47626. var shape = options.shape;
  47627. var holes = options.holes || [];
  47628. var depth = options.depth || 0;
  47629. var contours = [];
  47630. var hole = [];
  47631. for (var i = 0; i < shape.length; i++) {
  47632. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47633. }
  47634. var epsilon = 0.00000001;
  47635. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47636. contours.pop();
  47637. }
  47638. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47639. for (var hNb = 0; hNb < holes.length; hNb++) {
  47640. hole = [];
  47641. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47642. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47643. }
  47644. polygonTriangulation.addHole(hole);
  47645. }
  47646. var polygon = polygonTriangulation.build(options.updatable, depth);
  47647. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47648. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47649. vertexData.applyToMesh(polygon, options.updatable);
  47650. return polygon;
  47651. };
  47652. ;
  47653. /**
  47654. * Creates an extruded polygon mesh, with depth in the Y direction.
  47655. * 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).
  47656. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47657. */
  47658. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47659. return MeshBuilder.CreatePolygon(name, options, scene);
  47660. };
  47661. ;
  47662. /**
  47663. * Creates a tube mesh.
  47664. * 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.
  47665. *
  47666. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47667. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47668. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47669. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47670. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47671. * 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.
  47672. * It must return a radius value (positive float) :
  47673. * ```javascript
  47674. * var radiusFunction = function(i, distance) {
  47675. * // do things
  47676. * return radius; }
  47677. * ```
  47678. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47679. * 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
  47680. * 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
  47681. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47682. * 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).
  47683. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47684. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47686. */
  47687. MeshBuilder.CreateTube = function (name, options, scene) {
  47688. var path = options.path;
  47689. var instance = options.instance;
  47690. var radius = 1.0;
  47691. if (instance) {
  47692. radius = instance.radius;
  47693. }
  47694. if (options.radius !== undefined) {
  47695. radius = options.radius;
  47696. }
  47697. ;
  47698. var tessellation = options.tessellation || 64 | 0;
  47699. var radiusFunction = options.radiusFunction || null;
  47700. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47701. var invertUV = options.invertUV || false;
  47702. var updatable = options.updatable;
  47703. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47704. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47705. // tube geometry
  47706. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47707. var tangents = path3D.getTangents();
  47708. var normals = path3D.getNormals();
  47709. var distances = path3D.getDistances();
  47710. var pi2 = Math.PI * 2;
  47711. var step = pi2 / tessellation * arc;
  47712. var returnRadius = function () { return radius; };
  47713. var radiusFunctionFinal = radiusFunction || returnRadius;
  47714. var circlePath;
  47715. var rad;
  47716. var normal;
  47717. var rotated;
  47718. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47719. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47720. for (var i = 0; i < path.length; i++) {
  47721. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47722. circlePath = Array(); // current circle array
  47723. normal = normals[i]; // current normal
  47724. for (var t = 0; t < tessellation; t++) {
  47725. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47726. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47727. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47728. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47729. circlePath[t] = rotated;
  47730. }
  47731. circlePaths[index] = circlePath;
  47732. index++;
  47733. }
  47734. // cap
  47735. var capPath = function (nbPoints, pathIndex) {
  47736. var pointCap = Array();
  47737. for (var i = 0; i < nbPoints; i++) {
  47738. pointCap.push(path[pathIndex]);
  47739. }
  47740. return pointCap;
  47741. };
  47742. switch (cap) {
  47743. case BABYLON.Mesh.NO_CAP:
  47744. break;
  47745. case BABYLON.Mesh.CAP_START:
  47746. circlePaths[0] = capPath(tessellation, 0);
  47747. circlePaths[1] = circlePaths[2].slice(0);
  47748. break;
  47749. case BABYLON.Mesh.CAP_END:
  47750. circlePaths[index] = circlePaths[index - 1].slice(0);
  47751. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47752. break;
  47753. case BABYLON.Mesh.CAP_ALL:
  47754. circlePaths[0] = capPath(tessellation, 0);
  47755. circlePaths[1] = circlePaths[2].slice(0);
  47756. circlePaths[index] = circlePaths[index - 1].slice(0);
  47757. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47758. break;
  47759. default:
  47760. break;
  47761. }
  47762. return circlePaths;
  47763. };
  47764. var path3D;
  47765. var pathArray;
  47766. if (instance) {
  47767. var arc = options.arc || instance.arc;
  47768. path3D = (instance.path3D).update(path);
  47769. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47770. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47771. instance.path3D = path3D;
  47772. instance.pathArray = pathArray;
  47773. instance.arc = arc;
  47774. instance.radius = radius;
  47775. return instance;
  47776. }
  47777. // tube creation
  47778. path3D = new BABYLON.Path3D(path);
  47779. var newPathArray = new Array();
  47780. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47781. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47782. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47783. tube.pathArray = pathArray;
  47784. tube.path3D = path3D;
  47785. tube.tessellation = tessellation;
  47786. tube.cap = cap;
  47787. tube.arc = options.arc;
  47788. tube.radius = radius;
  47789. return tube;
  47790. };
  47791. /**
  47792. * Creates a polyhedron mesh.
  47793. *
  47794. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47795. * 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
  47796. * to choose the wanted type.
  47797. * The parameter `size` (positive float, default 1) sets the polygon size.
  47798. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47799. * 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`.
  47800. * 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
  47801. * 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)`).
  47802. * 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
  47803. * 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.
  47804. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47805. * 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).
  47806. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47808. */
  47809. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47810. var polyhedron = new BABYLON.Mesh(name, scene);
  47811. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47812. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47813. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47814. vertexData.applyToMesh(polyhedron, options.updatable);
  47815. return polyhedron;
  47816. };
  47817. /**
  47818. * Creates a decal mesh.
  47819. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47820. * 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.
  47821. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47822. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47823. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47824. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47825. */
  47826. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47827. var indices = sourceMesh.getIndices();
  47828. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47829. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47830. var position = options.position || BABYLON.Vector3.Zero();
  47831. var normal = options.normal || BABYLON.Vector3.Up();
  47832. var size = options.size || BABYLON.Vector3.One();
  47833. var angle = options.angle || 0;
  47834. // Getting correct rotation
  47835. if (!normal) {
  47836. var target = new BABYLON.Vector3(0, 0, 1);
  47837. var camera = sourceMesh.getScene().activeCamera;
  47838. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47839. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47840. }
  47841. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47842. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47843. var pitch = Math.atan2(normal.y, len);
  47844. // Matrix
  47845. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47846. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47847. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47848. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47849. var vertexData = new BABYLON.VertexData();
  47850. vertexData.indices = [];
  47851. vertexData.positions = [];
  47852. vertexData.normals = [];
  47853. vertexData.uvs = [];
  47854. var currentVertexDataIndex = 0;
  47855. var extractDecalVector3 = function (indexId) {
  47856. var result = new BABYLON.PositionNormalVertex();
  47857. if (!indices || !positions || !normals) {
  47858. return result;
  47859. }
  47860. var vertexId = indices[indexId];
  47861. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47862. // Send vector to decal local world
  47863. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47864. // Get normal
  47865. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47866. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47867. return result;
  47868. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47869. var clip = function (vertices, axis) {
  47870. if (vertices.length === 0) {
  47871. return vertices;
  47872. }
  47873. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47874. var clipVertices = function (v0, v1) {
  47875. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47876. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47877. };
  47878. var result = new Array();
  47879. for (var index = 0; index < vertices.length; index += 3) {
  47880. var v1Out;
  47881. var v2Out;
  47882. var v3Out;
  47883. var total = 0;
  47884. var nV1 = null;
  47885. var nV2 = null;
  47886. var nV3 = null;
  47887. var nV4 = null;
  47888. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47889. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47890. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47891. v1Out = d1 > 0;
  47892. v2Out = d2 > 0;
  47893. v3Out = d3 > 0;
  47894. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47895. switch (total) {
  47896. case 0:
  47897. result.push(vertices[index]);
  47898. result.push(vertices[index + 1]);
  47899. result.push(vertices[index + 2]);
  47900. break;
  47901. case 1:
  47902. if (v1Out) {
  47903. nV1 = vertices[index + 1];
  47904. nV2 = vertices[index + 2];
  47905. nV3 = clipVertices(vertices[index], nV1);
  47906. nV4 = clipVertices(vertices[index], nV2);
  47907. }
  47908. if (v2Out) {
  47909. nV1 = vertices[index];
  47910. nV2 = vertices[index + 2];
  47911. nV3 = clipVertices(vertices[index + 1], nV1);
  47912. nV4 = clipVertices(vertices[index + 1], nV2);
  47913. result.push(nV3);
  47914. result.push(nV2.clone());
  47915. result.push(nV1.clone());
  47916. result.push(nV2.clone());
  47917. result.push(nV3.clone());
  47918. result.push(nV4);
  47919. break;
  47920. }
  47921. if (v3Out) {
  47922. nV1 = vertices[index];
  47923. nV2 = vertices[index + 1];
  47924. nV3 = clipVertices(vertices[index + 2], nV1);
  47925. nV4 = clipVertices(vertices[index + 2], nV2);
  47926. }
  47927. if (nV1 && nV2 && nV3 && nV4) {
  47928. result.push(nV1.clone());
  47929. result.push(nV2.clone());
  47930. result.push(nV3);
  47931. result.push(nV4);
  47932. result.push(nV3.clone());
  47933. result.push(nV2.clone());
  47934. }
  47935. break;
  47936. case 2:
  47937. if (!v1Out) {
  47938. nV1 = vertices[index].clone();
  47939. nV2 = clipVertices(nV1, vertices[index + 1]);
  47940. nV3 = clipVertices(nV1, vertices[index + 2]);
  47941. result.push(nV1);
  47942. result.push(nV2);
  47943. result.push(nV3);
  47944. }
  47945. if (!v2Out) {
  47946. nV1 = vertices[index + 1].clone();
  47947. nV2 = clipVertices(nV1, vertices[index + 2]);
  47948. nV3 = clipVertices(nV1, vertices[index]);
  47949. result.push(nV1);
  47950. result.push(nV2);
  47951. result.push(nV3);
  47952. }
  47953. if (!v3Out) {
  47954. nV1 = vertices[index + 2].clone();
  47955. nV2 = clipVertices(nV1, vertices[index]);
  47956. nV3 = clipVertices(nV1, vertices[index + 1]);
  47957. result.push(nV1);
  47958. result.push(nV2);
  47959. result.push(nV3);
  47960. }
  47961. break;
  47962. case 3:
  47963. break;
  47964. }
  47965. }
  47966. return result;
  47967. };
  47968. for (var index = 0; index < indices.length; index += 3) {
  47969. var faceVertices = new Array();
  47970. faceVertices.push(extractDecalVector3(index));
  47971. faceVertices.push(extractDecalVector3(index + 1));
  47972. faceVertices.push(extractDecalVector3(index + 2));
  47973. // Clip
  47974. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47975. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47976. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47977. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47978. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47979. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47980. if (faceVertices.length === 0) {
  47981. continue;
  47982. }
  47983. // Add UVs and get back to world
  47984. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47985. var vertex = faceVertices[vIndex];
  47986. //TODO check for Int32Array | Uint32Array | Uint16Array
  47987. vertexData.indices.push(currentVertexDataIndex);
  47988. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47989. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47990. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47991. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47992. currentVertexDataIndex++;
  47993. }
  47994. }
  47995. // Return mesh
  47996. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47997. vertexData.applyToMesh(decal);
  47998. decal.position = position.clone();
  47999. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48000. return decal;
  48001. };
  48002. // Privates
  48003. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48004. // extrusion geometry
  48005. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48006. var tangents = path3D.getTangents();
  48007. var normals = path3D.getNormals();
  48008. var binormals = path3D.getBinormals();
  48009. var distances = path3D.getDistances();
  48010. var angle = 0;
  48011. var returnScale = function () { return scale !== null ? scale : 1; };
  48012. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48013. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48014. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48015. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48016. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48017. for (var i = 0; i < curve.length; i++) {
  48018. var shapePath = new Array();
  48019. var angleStep = rotate(i, distances[i]);
  48020. var scaleRatio = scl(i, distances[i]);
  48021. for (var p = 0; p < shape.length; p++) {
  48022. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48023. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48024. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48025. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48026. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48027. shapePath[p] = rotated;
  48028. }
  48029. shapePaths[index] = shapePath;
  48030. angle += angleStep;
  48031. index++;
  48032. }
  48033. // cap
  48034. var capPath = function (shapePath) {
  48035. var pointCap = Array();
  48036. var barycenter = BABYLON.Vector3.Zero();
  48037. var i;
  48038. for (i = 0; i < shapePath.length; i++) {
  48039. barycenter.addInPlace(shapePath[i]);
  48040. }
  48041. barycenter.scaleInPlace(1.0 / shapePath.length);
  48042. for (i = 0; i < shapePath.length; i++) {
  48043. pointCap.push(barycenter);
  48044. }
  48045. return pointCap;
  48046. };
  48047. switch (cap) {
  48048. case BABYLON.Mesh.NO_CAP:
  48049. break;
  48050. case BABYLON.Mesh.CAP_START:
  48051. shapePaths[0] = capPath(shapePaths[2]);
  48052. shapePaths[1] = shapePaths[2];
  48053. break;
  48054. case BABYLON.Mesh.CAP_END:
  48055. shapePaths[index] = shapePaths[index - 1];
  48056. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48057. break;
  48058. case BABYLON.Mesh.CAP_ALL:
  48059. shapePaths[0] = capPath(shapePaths[2]);
  48060. shapePaths[1] = shapePaths[2];
  48061. shapePaths[index] = shapePaths[index - 1];
  48062. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48063. break;
  48064. default:
  48065. break;
  48066. }
  48067. return shapePaths;
  48068. };
  48069. var path3D;
  48070. var pathArray;
  48071. if (instance) {
  48072. path3D = (instance.path3D).update(curve);
  48073. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48074. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48075. return instance;
  48076. }
  48077. // extruded shape creation
  48078. path3D = new BABYLON.Path3D(curve);
  48079. var newShapePaths = new Array();
  48080. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48081. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48082. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48083. extrudedGeneric.pathArray = pathArray;
  48084. extrudedGeneric.path3D = path3D;
  48085. extrudedGeneric.cap = cap;
  48086. return extrudedGeneric;
  48087. };
  48088. return MeshBuilder;
  48089. }());
  48090. BABYLON.MeshBuilder = MeshBuilder;
  48091. })(BABYLON || (BABYLON = {}));
  48092. //# sourceMappingURL=babylon.meshBuilder.js.map
  48093. var BABYLON;
  48094. (function (BABYLON) {
  48095. var AudioEngine = /** @class */ (function () {
  48096. function AudioEngine() {
  48097. this._audioContext = null;
  48098. this._audioContextInitialized = false;
  48099. this.canUseWebAudio = false;
  48100. this.WarnedWebAudioUnsupported = false;
  48101. this.unlocked = false;
  48102. this.isMP3supported = false;
  48103. this.isOGGsupported = false;
  48104. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48105. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48106. this.canUseWebAudio = true;
  48107. }
  48108. var audioElem = document.createElement('audio');
  48109. try {
  48110. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48111. this.isMP3supported = true;
  48112. }
  48113. }
  48114. catch (e) {
  48115. // protect error during capability check.
  48116. }
  48117. try {
  48118. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48119. this.isOGGsupported = true;
  48120. }
  48121. }
  48122. catch (e) {
  48123. // protect error during capability check.
  48124. }
  48125. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48126. this._unlockiOSaudio();
  48127. }
  48128. else {
  48129. this.unlocked = true;
  48130. }
  48131. }
  48132. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48133. get: function () {
  48134. if (!this._audioContextInitialized) {
  48135. this._initializeAudioContext();
  48136. }
  48137. return this._audioContext;
  48138. },
  48139. enumerable: true,
  48140. configurable: true
  48141. });
  48142. AudioEngine.prototype._unlockiOSaudio = function () {
  48143. var _this = this;
  48144. var unlockaudio = function () {
  48145. if (!_this.audioContext) {
  48146. return;
  48147. }
  48148. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48149. var source = _this.audioContext.createBufferSource();
  48150. source.buffer = buffer;
  48151. source.connect(_this.audioContext.destination);
  48152. source.start(0);
  48153. setTimeout(function () {
  48154. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48155. _this.unlocked = true;
  48156. window.removeEventListener('touchend', unlockaudio, false);
  48157. if (_this.onAudioUnlocked) {
  48158. _this.onAudioUnlocked();
  48159. }
  48160. }
  48161. }, 0);
  48162. };
  48163. window.addEventListener('touchend', unlockaudio, false);
  48164. };
  48165. AudioEngine.prototype._initializeAudioContext = function () {
  48166. try {
  48167. if (this.canUseWebAudio) {
  48168. this._audioContext = new AudioContext();
  48169. // create a global volume gain node
  48170. this.masterGain = this._audioContext.createGain();
  48171. this.masterGain.gain.value = 1;
  48172. this.masterGain.connect(this._audioContext.destination);
  48173. this._audioContextInitialized = true;
  48174. }
  48175. }
  48176. catch (e) {
  48177. this.canUseWebAudio = false;
  48178. BABYLON.Tools.Error("Web Audio: " + e.message);
  48179. }
  48180. };
  48181. AudioEngine.prototype.dispose = function () {
  48182. if (this.canUseWebAudio && this._audioContextInitialized) {
  48183. if (this._connectedAnalyser && this._audioContext) {
  48184. this._connectedAnalyser.stopDebugCanvas();
  48185. this._connectedAnalyser.dispose();
  48186. this.masterGain.disconnect();
  48187. this.masterGain.connect(this._audioContext.destination);
  48188. this._connectedAnalyser = null;
  48189. }
  48190. this.masterGain.gain.value = 1;
  48191. }
  48192. this.WarnedWebAudioUnsupported = false;
  48193. };
  48194. AudioEngine.prototype.getGlobalVolume = function () {
  48195. if (this.canUseWebAudio && this._audioContextInitialized) {
  48196. return this.masterGain.gain.value;
  48197. }
  48198. else {
  48199. return -1;
  48200. }
  48201. };
  48202. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48203. if (this.canUseWebAudio && this._audioContextInitialized) {
  48204. this.masterGain.gain.value = newVolume;
  48205. }
  48206. };
  48207. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48208. if (this._connectedAnalyser) {
  48209. this._connectedAnalyser.stopDebugCanvas();
  48210. }
  48211. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48212. this._connectedAnalyser = analyser;
  48213. this.masterGain.disconnect();
  48214. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48215. }
  48216. };
  48217. return AudioEngine;
  48218. }());
  48219. BABYLON.AudioEngine = AudioEngine;
  48220. })(BABYLON || (BABYLON = {}));
  48221. //# sourceMappingURL=babylon.audioEngine.js.map
  48222. var BABYLON;
  48223. (function (BABYLON) {
  48224. var Sound = /** @class */ (function () {
  48225. /**
  48226. * Create a sound and attach it to a scene
  48227. * @param name Name of your sound
  48228. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48229. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48230. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48231. */
  48232. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48233. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48234. var _this = this;
  48235. this.autoplay = false;
  48236. this.loop = false;
  48237. this.useCustomAttenuation = false;
  48238. this.spatialSound = false;
  48239. this.refDistance = 1;
  48240. this.rolloffFactor = 1;
  48241. this.maxDistance = 100;
  48242. this.distanceModel = "linear";
  48243. this._panningModel = "equalpower";
  48244. this._playbackRate = 1;
  48245. this._streaming = false;
  48246. this._startTime = 0;
  48247. this._startOffset = 0;
  48248. this._position = BABYLON.Vector3.Zero();
  48249. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48250. this._volume = 1;
  48251. this._isLoaded = false;
  48252. this._isReadyToPlay = false;
  48253. this.isPlaying = false;
  48254. this.isPaused = false;
  48255. this._isDirectional = false;
  48256. // Used if you'd like to create a directional sound.
  48257. // If not set, the sound will be omnidirectional
  48258. this._coneInnerAngle = 360;
  48259. this._coneOuterAngle = 360;
  48260. this._coneOuterGain = 0;
  48261. this._isOutputConnected = false;
  48262. this._urlType = "Unknown";
  48263. this.name = name;
  48264. this._scene = scene;
  48265. this._readyToPlayCallback = readyToPlayCallback;
  48266. // Default custom attenuation function is a linear attenuation
  48267. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48268. if (currentDistance < maxDistance) {
  48269. return currentVolume * (1 - currentDistance / maxDistance);
  48270. }
  48271. else {
  48272. return 0;
  48273. }
  48274. };
  48275. if (options) {
  48276. this.autoplay = options.autoplay || false;
  48277. this.loop = options.loop || false;
  48278. // if volume === 0, we need another way to check this option
  48279. if (options.volume !== undefined) {
  48280. this._volume = options.volume;
  48281. }
  48282. this.spatialSound = options.spatialSound || false;
  48283. this.maxDistance = options.maxDistance || 100;
  48284. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48285. this.rolloffFactor = options.rolloffFactor || 1;
  48286. this.refDistance = options.refDistance || 1;
  48287. this.distanceModel = options.distanceModel || "linear";
  48288. this._playbackRate = options.playbackRate || 1;
  48289. this._streaming = options.streaming || false;
  48290. }
  48291. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48292. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48293. this._soundGain.gain.value = this._volume;
  48294. this._inputAudioNode = this._soundGain;
  48295. this._ouputAudioNode = this._soundGain;
  48296. if (this.spatialSound) {
  48297. this._createSpatialParameters();
  48298. }
  48299. this._scene.mainSoundTrack.AddSound(this);
  48300. var validParameter = true;
  48301. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48302. if (urlOrArrayBuffer) {
  48303. if (typeof (urlOrArrayBuffer) === "string")
  48304. this._urlType = "String";
  48305. if (Array.isArray(urlOrArrayBuffer))
  48306. this._urlType = "Array";
  48307. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48308. this._urlType = "ArrayBuffer";
  48309. var urls = [];
  48310. var codecSupportedFound = false;
  48311. switch (this._urlType) {
  48312. case "ArrayBuffer":
  48313. if (urlOrArrayBuffer.byteLength > 0) {
  48314. codecSupportedFound = true;
  48315. this._soundLoaded(urlOrArrayBuffer);
  48316. }
  48317. break;
  48318. case "String":
  48319. urls.push(urlOrArrayBuffer);
  48320. case "Array":
  48321. if (urls.length === 0)
  48322. urls = urlOrArrayBuffer;
  48323. // If we found a supported format, we load it immediately and stop the loop
  48324. for (var i = 0; i < urls.length; i++) {
  48325. var url = urls[i];
  48326. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48327. codecSupportedFound = true;
  48328. }
  48329. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48330. codecSupportedFound = true;
  48331. }
  48332. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48333. codecSupportedFound = true;
  48334. }
  48335. if (url.indexOf("blob:") !== -1) {
  48336. codecSupportedFound = true;
  48337. }
  48338. if (codecSupportedFound) {
  48339. // Loading sound using XHR2
  48340. if (!this._streaming) {
  48341. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48342. }
  48343. else {
  48344. this._htmlAudioElement = new Audio(url);
  48345. this._htmlAudioElement.controls = false;
  48346. this._htmlAudioElement.loop = this.loop;
  48347. this._htmlAudioElement.crossOrigin = "anonymous";
  48348. this._htmlAudioElement.preload = "auto";
  48349. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48350. _this._isReadyToPlay = true;
  48351. if (_this.autoplay) {
  48352. _this.play();
  48353. }
  48354. if (_this._readyToPlayCallback) {
  48355. _this._readyToPlayCallback();
  48356. }
  48357. });
  48358. document.body.appendChild(this._htmlAudioElement);
  48359. }
  48360. break;
  48361. }
  48362. }
  48363. break;
  48364. default:
  48365. validParameter = false;
  48366. break;
  48367. }
  48368. if (!validParameter) {
  48369. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48370. }
  48371. else {
  48372. if (!codecSupportedFound) {
  48373. this._isReadyToPlay = true;
  48374. // Simulating a ready to play event to avoid breaking code path
  48375. if (this._readyToPlayCallback) {
  48376. window.setTimeout(function () {
  48377. if (_this._readyToPlayCallback) {
  48378. _this._readyToPlayCallback();
  48379. }
  48380. }, 1000);
  48381. }
  48382. }
  48383. }
  48384. }
  48385. }
  48386. else {
  48387. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48388. this._scene.mainSoundTrack.AddSound(this);
  48389. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48390. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48391. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48392. }
  48393. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48394. if (this._readyToPlayCallback) {
  48395. window.setTimeout(function () {
  48396. if (_this._readyToPlayCallback) {
  48397. _this._readyToPlayCallback();
  48398. }
  48399. }, 1000);
  48400. }
  48401. }
  48402. }
  48403. Sound.prototype.dispose = function () {
  48404. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48405. if (this.isPlaying) {
  48406. this.stop();
  48407. }
  48408. this._isReadyToPlay = false;
  48409. if (this.soundTrackId === -1) {
  48410. this._scene.mainSoundTrack.RemoveSound(this);
  48411. }
  48412. else {
  48413. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48414. }
  48415. if (this._soundGain) {
  48416. this._soundGain.disconnect();
  48417. this._soundGain = null;
  48418. }
  48419. if (this._soundPanner) {
  48420. this._soundPanner.disconnect();
  48421. this._soundPanner = null;
  48422. }
  48423. if (this._soundSource) {
  48424. this._soundSource.disconnect();
  48425. this._soundSource = null;
  48426. }
  48427. this._audioBuffer = null;
  48428. if (this._htmlAudioElement) {
  48429. this._htmlAudioElement.pause();
  48430. this._htmlAudioElement.src = "";
  48431. document.body.removeChild(this._htmlAudioElement);
  48432. }
  48433. if (this._connectedMesh && this._registerFunc) {
  48434. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48435. this._connectedMesh = null;
  48436. }
  48437. }
  48438. };
  48439. Sound.prototype.isReady = function () {
  48440. return this._isReadyToPlay;
  48441. };
  48442. Sound.prototype._soundLoaded = function (audioData) {
  48443. var _this = this;
  48444. this._isLoaded = true;
  48445. if (!BABYLON.Engine.audioEngine.audioContext) {
  48446. return;
  48447. }
  48448. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48449. _this._audioBuffer = buffer;
  48450. _this._isReadyToPlay = true;
  48451. if (_this.autoplay) {
  48452. _this.play();
  48453. }
  48454. if (_this._readyToPlayCallback) {
  48455. _this._readyToPlayCallback();
  48456. }
  48457. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48458. };
  48459. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48460. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48461. this._audioBuffer = audioBuffer;
  48462. this._isReadyToPlay = true;
  48463. }
  48464. };
  48465. Sound.prototype.updateOptions = function (options) {
  48466. if (options) {
  48467. this.loop = options.loop || this.loop;
  48468. this.maxDistance = options.maxDistance || this.maxDistance;
  48469. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48470. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48471. this.refDistance = options.refDistance || this.refDistance;
  48472. this.distanceModel = options.distanceModel || this.distanceModel;
  48473. this._playbackRate = options.playbackRate || this._playbackRate;
  48474. this._updateSpatialParameters();
  48475. if (this.isPlaying) {
  48476. if (this._streaming) {
  48477. this._htmlAudioElement.playbackRate = this._playbackRate;
  48478. }
  48479. else {
  48480. if (this._soundSource) {
  48481. this._soundSource.playbackRate.value = this._playbackRate;
  48482. }
  48483. }
  48484. }
  48485. }
  48486. };
  48487. Sound.prototype._createSpatialParameters = function () {
  48488. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48489. if (this._scene.headphone) {
  48490. this._panningModel = "HRTF";
  48491. }
  48492. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48493. this._updateSpatialParameters();
  48494. this._soundPanner.connect(this._ouputAudioNode);
  48495. this._inputAudioNode = this._soundPanner;
  48496. }
  48497. };
  48498. Sound.prototype._updateSpatialParameters = function () {
  48499. if (this.spatialSound && this._soundPanner) {
  48500. if (this.useCustomAttenuation) {
  48501. // Tricks to disable in a way embedded Web Audio attenuation
  48502. this._soundPanner.distanceModel = "linear";
  48503. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48504. this._soundPanner.refDistance = 1;
  48505. this._soundPanner.rolloffFactor = 1;
  48506. this._soundPanner.panningModel = this._panningModel;
  48507. }
  48508. else {
  48509. this._soundPanner.distanceModel = this.distanceModel;
  48510. this._soundPanner.maxDistance = this.maxDistance;
  48511. this._soundPanner.refDistance = this.refDistance;
  48512. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48513. this._soundPanner.panningModel = this._panningModel;
  48514. }
  48515. }
  48516. };
  48517. Sound.prototype.switchPanningModelToHRTF = function () {
  48518. this._panningModel = "HRTF";
  48519. this._switchPanningModel();
  48520. };
  48521. Sound.prototype.switchPanningModelToEqualPower = function () {
  48522. this._panningModel = "equalpower";
  48523. this._switchPanningModel();
  48524. };
  48525. Sound.prototype._switchPanningModel = function () {
  48526. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48527. this._soundPanner.panningModel = this._panningModel;
  48528. }
  48529. };
  48530. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48531. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48532. if (this._isOutputConnected) {
  48533. this._ouputAudioNode.disconnect();
  48534. }
  48535. this._ouputAudioNode.connect(soundTrackAudioNode);
  48536. this._isOutputConnected = true;
  48537. }
  48538. };
  48539. /**
  48540. * Transform this sound into a directional source
  48541. * @param coneInnerAngle Size of the inner cone in degree
  48542. * @param coneOuterAngle Size of the outer cone in degree
  48543. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48544. */
  48545. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48546. if (coneOuterAngle < coneInnerAngle) {
  48547. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48548. return;
  48549. }
  48550. this._coneInnerAngle = coneInnerAngle;
  48551. this._coneOuterAngle = coneOuterAngle;
  48552. this._coneOuterGain = coneOuterGain;
  48553. this._isDirectional = true;
  48554. if (this.isPlaying && this.loop) {
  48555. this.stop();
  48556. this.play();
  48557. }
  48558. };
  48559. Sound.prototype.setPosition = function (newPosition) {
  48560. this._position = newPosition;
  48561. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48562. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48563. }
  48564. };
  48565. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48566. this._localDirection = newLocalDirection;
  48567. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48568. this._updateDirection();
  48569. }
  48570. };
  48571. Sound.prototype._updateDirection = function () {
  48572. if (!this._connectedMesh || !this._soundPanner) {
  48573. return;
  48574. }
  48575. var mat = this._connectedMesh.getWorldMatrix();
  48576. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48577. direction.normalize();
  48578. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48579. };
  48580. Sound.prototype.updateDistanceFromListener = function () {
  48581. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48582. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48583. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48584. }
  48585. };
  48586. Sound.prototype.setAttenuationFunction = function (callback) {
  48587. this._customAttenuationFunction = callback;
  48588. };
  48589. /**
  48590. * Play the sound
  48591. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48592. * @param offset (optional) Start the sound setting it at a specific time
  48593. */
  48594. Sound.prototype.play = function (time, offset) {
  48595. var _this = this;
  48596. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48597. try {
  48598. if (this._startOffset < 0) {
  48599. time = -this._startOffset;
  48600. this._startOffset = 0;
  48601. }
  48602. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48603. if (!this._soundSource || !this._streamingSource) {
  48604. if (this.spatialSound && this._soundPanner) {
  48605. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48606. if (this._isDirectional) {
  48607. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48608. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48609. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48610. if (this._connectedMesh) {
  48611. this._updateDirection();
  48612. }
  48613. else {
  48614. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48615. }
  48616. }
  48617. }
  48618. }
  48619. if (this._streaming) {
  48620. if (!this._streamingSource) {
  48621. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48622. this._htmlAudioElement.onended = function () { _this._onended(); };
  48623. this._htmlAudioElement.playbackRate = this._playbackRate;
  48624. }
  48625. this._streamingSource.disconnect();
  48626. this._streamingSource.connect(this._inputAudioNode);
  48627. this._htmlAudioElement.play();
  48628. }
  48629. else {
  48630. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48631. this._soundSource.buffer = this._audioBuffer;
  48632. this._soundSource.connect(this._inputAudioNode);
  48633. this._soundSource.loop = this.loop;
  48634. this._soundSource.playbackRate.value = this._playbackRate;
  48635. this._soundSource.onended = function () { _this._onended(); };
  48636. if (this._soundSource.buffer) {
  48637. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48638. }
  48639. }
  48640. this._startTime = startTime;
  48641. this.isPlaying = true;
  48642. this.isPaused = false;
  48643. }
  48644. catch (ex) {
  48645. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48646. }
  48647. }
  48648. };
  48649. Sound.prototype._onended = function () {
  48650. this.isPlaying = false;
  48651. if (this.onended) {
  48652. this.onended();
  48653. }
  48654. };
  48655. /**
  48656. * Stop the sound
  48657. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48658. */
  48659. Sound.prototype.stop = function (time) {
  48660. if (this.isPlaying) {
  48661. if (this._streaming) {
  48662. this._htmlAudioElement.pause();
  48663. // Test needed for Firefox or it will generate an Invalid State Error
  48664. if (this._htmlAudioElement.currentTime > 0) {
  48665. this._htmlAudioElement.currentTime = 0;
  48666. }
  48667. }
  48668. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48669. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48670. this._soundSource.stop(stopTime);
  48671. this._soundSource.onended = function () { };
  48672. if (!this.isPaused) {
  48673. this._startOffset = 0;
  48674. }
  48675. }
  48676. this.isPlaying = false;
  48677. }
  48678. };
  48679. Sound.prototype.pause = function () {
  48680. if (this.isPlaying) {
  48681. this.isPaused = true;
  48682. if (this._streaming) {
  48683. this._htmlAudioElement.pause();
  48684. }
  48685. else if (BABYLON.Engine.audioEngine.audioContext) {
  48686. this.stop(0);
  48687. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48688. }
  48689. }
  48690. };
  48691. Sound.prototype.setVolume = function (newVolume, time) {
  48692. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48693. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48694. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48695. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48696. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48697. }
  48698. else {
  48699. this._soundGain.gain.value = newVolume;
  48700. }
  48701. }
  48702. this._volume = newVolume;
  48703. };
  48704. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48705. this._playbackRate = newPlaybackRate;
  48706. if (this.isPlaying) {
  48707. if (this._streaming) {
  48708. this._htmlAudioElement.playbackRate = this._playbackRate;
  48709. }
  48710. else if (this._soundSource) {
  48711. this._soundSource.playbackRate.value = this._playbackRate;
  48712. }
  48713. }
  48714. };
  48715. Sound.prototype.getVolume = function () {
  48716. return this._volume;
  48717. };
  48718. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48719. var _this = this;
  48720. if (this._connectedMesh && this._registerFunc) {
  48721. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48722. this._registerFunc = null;
  48723. }
  48724. this._connectedMesh = meshToConnectTo;
  48725. if (!this.spatialSound) {
  48726. this.spatialSound = true;
  48727. this._createSpatialParameters();
  48728. if (this.isPlaying && this.loop) {
  48729. this.stop();
  48730. this.play();
  48731. }
  48732. }
  48733. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48734. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48735. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48736. };
  48737. Sound.prototype.detachFromMesh = function () {
  48738. if (this._connectedMesh && this._registerFunc) {
  48739. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48740. this._registerFunc = null;
  48741. this._connectedMesh = null;
  48742. }
  48743. };
  48744. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48745. var boundingInfo = connectedMesh.getBoundingInfo();
  48746. if (!boundingInfo) {
  48747. return;
  48748. }
  48749. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48750. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48751. this._updateDirection();
  48752. }
  48753. };
  48754. Sound.prototype.clone = function () {
  48755. var _this = this;
  48756. if (!this._streaming) {
  48757. var setBufferAndRun = function () {
  48758. if (_this._isReadyToPlay) {
  48759. clonedSound._audioBuffer = _this.getAudioBuffer();
  48760. clonedSound._isReadyToPlay = true;
  48761. if (clonedSound.autoplay) {
  48762. clonedSound.play();
  48763. }
  48764. }
  48765. else {
  48766. window.setTimeout(setBufferAndRun, 300);
  48767. }
  48768. };
  48769. var currentOptions = {
  48770. autoplay: this.autoplay, loop: this.loop,
  48771. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48772. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48773. refDistance: this.refDistance, distanceModel: this.distanceModel
  48774. };
  48775. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48776. if (this.useCustomAttenuation) {
  48777. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48778. }
  48779. clonedSound.setPosition(this._position);
  48780. clonedSound.setPlaybackRate(this._playbackRate);
  48781. setBufferAndRun();
  48782. return clonedSound;
  48783. }
  48784. else {
  48785. return null;
  48786. }
  48787. };
  48788. Sound.prototype.getAudioBuffer = function () {
  48789. return this._audioBuffer;
  48790. };
  48791. Sound.prototype.serialize = function () {
  48792. var serializationObject = {
  48793. name: this.name,
  48794. url: this.name,
  48795. autoplay: this.autoplay,
  48796. loop: this.loop,
  48797. volume: this._volume,
  48798. spatialSound: this.spatialSound,
  48799. maxDistance: this.maxDistance,
  48800. rolloffFactor: this.rolloffFactor,
  48801. refDistance: this.refDistance,
  48802. distanceModel: this.distanceModel,
  48803. playbackRate: this._playbackRate,
  48804. panningModel: this._panningModel,
  48805. soundTrackId: this.soundTrackId
  48806. };
  48807. if (this.spatialSound) {
  48808. if (this._connectedMesh)
  48809. serializationObject.connectedMeshId = this._connectedMesh.id;
  48810. serializationObject.position = this._position.asArray();
  48811. serializationObject.refDistance = this.refDistance;
  48812. serializationObject.distanceModel = this.distanceModel;
  48813. serializationObject.isDirectional = this._isDirectional;
  48814. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48815. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48816. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48817. serializationObject.coneOuterGain = this._coneOuterGain;
  48818. }
  48819. return serializationObject;
  48820. };
  48821. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48822. var soundName = parsedSound.name;
  48823. var soundUrl;
  48824. if (parsedSound.url) {
  48825. soundUrl = rootUrl + parsedSound.url;
  48826. }
  48827. else {
  48828. soundUrl = rootUrl + soundName;
  48829. }
  48830. var options = {
  48831. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48832. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48833. rolloffFactor: parsedSound.rolloffFactor,
  48834. refDistance: parsedSound.refDistance,
  48835. distanceModel: parsedSound.distanceModel,
  48836. playbackRate: parsedSound.playbackRate
  48837. };
  48838. var newSound;
  48839. if (!sourceSound) {
  48840. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48841. scene._addPendingData(newSound);
  48842. }
  48843. else {
  48844. var setBufferAndRun = function () {
  48845. if (sourceSound._isReadyToPlay) {
  48846. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48847. newSound._isReadyToPlay = true;
  48848. if (newSound.autoplay) {
  48849. newSound.play();
  48850. }
  48851. }
  48852. else {
  48853. window.setTimeout(setBufferAndRun, 300);
  48854. }
  48855. };
  48856. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48857. setBufferAndRun();
  48858. }
  48859. if (parsedSound.position) {
  48860. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48861. newSound.setPosition(soundPosition);
  48862. }
  48863. if (parsedSound.isDirectional) {
  48864. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48865. if (parsedSound.localDirectionToMesh) {
  48866. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48867. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48868. }
  48869. }
  48870. if (parsedSound.connectedMeshId) {
  48871. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48872. if (connectedMesh) {
  48873. newSound.attachToMesh(connectedMesh);
  48874. }
  48875. }
  48876. return newSound;
  48877. };
  48878. return Sound;
  48879. }());
  48880. BABYLON.Sound = Sound;
  48881. })(BABYLON || (BABYLON = {}));
  48882. //# sourceMappingURL=babylon.sound.js.map
  48883. var BABYLON;
  48884. (function (BABYLON) {
  48885. var SoundTrack = /** @class */ (function () {
  48886. function SoundTrack(scene, options) {
  48887. this.id = -1;
  48888. this._isMainTrack = false;
  48889. this._isInitialized = false;
  48890. this._scene = scene;
  48891. this.soundCollection = new Array();
  48892. this._options = options;
  48893. if (!this._isMainTrack) {
  48894. this._scene.soundTracks.push(this);
  48895. this.id = this._scene.soundTracks.length - 1;
  48896. }
  48897. }
  48898. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48899. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48900. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48901. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48902. if (this._options) {
  48903. if (this._options.volume) {
  48904. this._outputAudioNode.gain.value = this._options.volume;
  48905. }
  48906. if (this._options.mainTrack) {
  48907. this._isMainTrack = this._options.mainTrack;
  48908. }
  48909. }
  48910. this._isInitialized = true;
  48911. }
  48912. };
  48913. SoundTrack.prototype.dispose = function () {
  48914. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48915. if (this._connectedAnalyser) {
  48916. this._connectedAnalyser.stopDebugCanvas();
  48917. }
  48918. while (this.soundCollection.length) {
  48919. this.soundCollection[0].dispose();
  48920. }
  48921. if (this._outputAudioNode) {
  48922. this._outputAudioNode.disconnect();
  48923. }
  48924. this._outputAudioNode = null;
  48925. }
  48926. };
  48927. SoundTrack.prototype.AddSound = function (sound) {
  48928. if (!this._isInitialized) {
  48929. this._initializeSoundTrackAudioGraph();
  48930. }
  48931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48932. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48933. }
  48934. if (sound.soundTrackId) {
  48935. if (sound.soundTrackId === -1) {
  48936. this._scene.mainSoundTrack.RemoveSound(sound);
  48937. }
  48938. else {
  48939. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48940. }
  48941. }
  48942. this.soundCollection.push(sound);
  48943. sound.soundTrackId = this.id;
  48944. };
  48945. SoundTrack.prototype.RemoveSound = function (sound) {
  48946. var index = this.soundCollection.indexOf(sound);
  48947. if (index !== -1) {
  48948. this.soundCollection.splice(index, 1);
  48949. }
  48950. };
  48951. SoundTrack.prototype.setVolume = function (newVolume) {
  48952. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48953. this._outputAudioNode.gain.value = newVolume;
  48954. }
  48955. };
  48956. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48957. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48958. for (var i = 0; i < this.soundCollection.length; i++) {
  48959. this.soundCollection[i].switchPanningModelToHRTF();
  48960. }
  48961. }
  48962. };
  48963. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48964. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48965. for (var i = 0; i < this.soundCollection.length; i++) {
  48966. this.soundCollection[i].switchPanningModelToEqualPower();
  48967. }
  48968. }
  48969. };
  48970. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48971. if (this._connectedAnalyser) {
  48972. this._connectedAnalyser.stopDebugCanvas();
  48973. }
  48974. this._connectedAnalyser = analyser;
  48975. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48976. this._outputAudioNode.disconnect();
  48977. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48978. }
  48979. };
  48980. return SoundTrack;
  48981. }());
  48982. BABYLON.SoundTrack = SoundTrack;
  48983. })(BABYLON || (BABYLON = {}));
  48984. //# sourceMappingURL=babylon.soundtrack.js.map
  48985. var BABYLON;
  48986. (function (BABYLON) {
  48987. var Analyser = /** @class */ (function () {
  48988. function Analyser(scene) {
  48989. this.SMOOTHING = 0.75;
  48990. this.FFT_SIZE = 512;
  48991. this.BARGRAPHAMPLITUDE = 256;
  48992. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48993. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48994. this._scene = scene;
  48995. this._audioEngine = BABYLON.Engine.audioEngine;
  48996. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48997. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48998. this._webAudioAnalyser.minDecibels = -140;
  48999. this._webAudioAnalyser.maxDecibels = 0;
  49000. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49001. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49002. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49003. }
  49004. }
  49005. Analyser.prototype.getFrequencyBinCount = function () {
  49006. if (this._audioEngine.canUseWebAudio) {
  49007. return this._webAudioAnalyser.frequencyBinCount;
  49008. }
  49009. else {
  49010. return 0;
  49011. }
  49012. };
  49013. Analyser.prototype.getByteFrequencyData = function () {
  49014. if (this._audioEngine.canUseWebAudio) {
  49015. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49016. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49017. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49018. }
  49019. return this._byteFreqs;
  49020. };
  49021. Analyser.prototype.getByteTimeDomainData = function () {
  49022. if (this._audioEngine.canUseWebAudio) {
  49023. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49024. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49025. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49026. }
  49027. return this._byteTime;
  49028. };
  49029. Analyser.prototype.getFloatFrequencyData = function () {
  49030. if (this._audioEngine.canUseWebAudio) {
  49031. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49032. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49033. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49034. }
  49035. return this._floatFreqs;
  49036. };
  49037. Analyser.prototype.drawDebugCanvas = function () {
  49038. var _this = this;
  49039. if (this._audioEngine.canUseWebAudio) {
  49040. if (!this._debugCanvas) {
  49041. this._debugCanvas = document.createElement("canvas");
  49042. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49043. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49044. this._debugCanvas.style.position = "absolute";
  49045. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49046. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49047. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49048. document.body.appendChild(this._debugCanvas);
  49049. this._registerFunc = function () {
  49050. _this.drawDebugCanvas();
  49051. };
  49052. this._scene.registerBeforeRender(this._registerFunc);
  49053. }
  49054. if (this._registerFunc && this._debugCanvasContext) {
  49055. var workingArray = this.getByteFrequencyData();
  49056. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49057. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49058. // Draw the frequency domain chart.
  49059. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49060. var value = workingArray[i];
  49061. var percent = value / this.BARGRAPHAMPLITUDE;
  49062. var height = this.DEBUGCANVASSIZE.height * percent;
  49063. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49064. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49065. var hue = i / this.getFrequencyBinCount() * 360;
  49066. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49067. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49068. }
  49069. }
  49070. }
  49071. };
  49072. Analyser.prototype.stopDebugCanvas = function () {
  49073. if (this._debugCanvas) {
  49074. if (this._registerFunc) {
  49075. this._scene.unregisterBeforeRender(this._registerFunc);
  49076. this._registerFunc = null;
  49077. }
  49078. document.body.removeChild(this._debugCanvas);
  49079. this._debugCanvas = null;
  49080. this._debugCanvasContext = null;
  49081. }
  49082. };
  49083. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49084. if (this._audioEngine.canUseWebAudio) {
  49085. inputAudioNode.connect(this._webAudioAnalyser);
  49086. this._webAudioAnalyser.connect(outputAudioNode);
  49087. }
  49088. };
  49089. Analyser.prototype.dispose = function () {
  49090. if (this._audioEngine.canUseWebAudio) {
  49091. this._webAudioAnalyser.disconnect();
  49092. }
  49093. };
  49094. return Analyser;
  49095. }());
  49096. BABYLON.Analyser = Analyser;
  49097. })(BABYLON || (BABYLON = {}));
  49098. //# sourceMappingURL=babylon.analyser.js.map
  49099. var BABYLON;
  49100. (function (BABYLON) {
  49101. var CubeTexture = /** @class */ (function (_super) {
  49102. __extends(CubeTexture, _super);
  49103. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49104. if (extensions === void 0) { extensions = null; }
  49105. if (noMipmap === void 0) { noMipmap = false; }
  49106. if (files === void 0) { files = null; }
  49107. if (onLoad === void 0) { onLoad = null; }
  49108. if (onError === void 0) { onError = null; }
  49109. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49110. if (prefiltered === void 0) { prefiltered = false; }
  49111. if (forcedExtension === void 0) { forcedExtension = null; }
  49112. var _this = _super.call(this, scene) || this;
  49113. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49114. _this.name = rootUrl;
  49115. _this.url = rootUrl;
  49116. _this._noMipmap = noMipmap;
  49117. _this.hasAlpha = false;
  49118. _this._format = format;
  49119. _this._prefiltered = prefiltered;
  49120. _this.isCube = true;
  49121. _this._textureMatrix = BABYLON.Matrix.Identity();
  49122. if (prefiltered) {
  49123. _this.gammaSpace = false;
  49124. }
  49125. if (!rootUrl && !files) {
  49126. return _this;
  49127. }
  49128. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49129. if (!files) {
  49130. if (!extensions) {
  49131. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49132. }
  49133. files = [];
  49134. for (var index = 0; index < extensions.length; index++) {
  49135. files.push(rootUrl + extensions[index]);
  49136. }
  49137. _this._extensions = extensions;
  49138. }
  49139. _this._files = files;
  49140. if (!_this._texture) {
  49141. if (!scene.useDelayedTextureLoading) {
  49142. if (prefiltered) {
  49143. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49144. }
  49145. else {
  49146. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49147. }
  49148. }
  49149. else {
  49150. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49151. }
  49152. }
  49153. else if (onLoad) {
  49154. if (_this._texture.isReady) {
  49155. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49156. }
  49157. else {
  49158. _this._texture.onLoadedObservable.add(onLoad);
  49159. }
  49160. }
  49161. return _this;
  49162. }
  49163. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49164. return new CubeTexture("", scene, null, noMipmap, files);
  49165. };
  49166. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49167. if (forcedExtension === void 0) { forcedExtension = null; }
  49168. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49169. };
  49170. // Methods
  49171. CubeTexture.prototype.delayLoad = function () {
  49172. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49173. return;
  49174. }
  49175. var scene = this.getScene();
  49176. if (!scene) {
  49177. return;
  49178. }
  49179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49180. this._texture = this._getFromCache(this.url, this._noMipmap);
  49181. if (!this._texture) {
  49182. if (this._prefiltered) {
  49183. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49184. }
  49185. else {
  49186. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49187. }
  49188. }
  49189. };
  49190. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49191. return this._textureMatrix;
  49192. };
  49193. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49194. this._textureMatrix = value;
  49195. };
  49196. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49197. var texture = BABYLON.SerializationHelper.Parse(function () {
  49198. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49199. }, parsedTexture, scene);
  49200. // Animations
  49201. if (parsedTexture.animations) {
  49202. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49203. var parsedAnimation = parsedTexture.animations[animationIndex];
  49204. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49205. }
  49206. }
  49207. return texture;
  49208. };
  49209. CubeTexture.prototype.clone = function () {
  49210. var _this = this;
  49211. return BABYLON.SerializationHelper.Clone(function () {
  49212. var scene = _this.getScene();
  49213. if (!scene) {
  49214. return _this;
  49215. }
  49216. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49217. }, this);
  49218. };
  49219. return CubeTexture;
  49220. }(BABYLON.BaseTexture));
  49221. BABYLON.CubeTexture = CubeTexture;
  49222. })(BABYLON || (BABYLON = {}));
  49223. //# sourceMappingURL=babylon.cubeTexture.js.map
  49224. var BABYLON;
  49225. (function (BABYLON) {
  49226. var RenderTargetTexture = /** @class */ (function (_super) {
  49227. __extends(RenderTargetTexture, _super);
  49228. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49229. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49230. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49231. if (isCube === void 0) { isCube = false; }
  49232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49233. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49234. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49235. if (isMulti === void 0) { isMulti = false; }
  49236. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49237. _this.isCube = isCube;
  49238. /**
  49239. * Use this list to define the list of mesh you want to render.
  49240. */
  49241. _this.renderList = new Array();
  49242. _this.renderParticles = true;
  49243. _this.renderSprites = false;
  49244. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49245. _this.ignoreCameraViewport = false;
  49246. // Events
  49247. /**
  49248. * An event triggered when the texture is unbind.
  49249. * @type {BABYLON.Observable}
  49250. */
  49251. _this.onBeforeBindObservable = new BABYLON.Observable();
  49252. /**
  49253. * An event triggered when the texture is unbind.
  49254. * @type {BABYLON.Observable}
  49255. */
  49256. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49257. /**
  49258. * An event triggered before rendering the texture
  49259. * @type {BABYLON.Observable}
  49260. */
  49261. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49262. /**
  49263. * An event triggered after rendering the texture
  49264. * @type {BABYLON.Observable}
  49265. */
  49266. _this.onAfterRenderObservable = new BABYLON.Observable();
  49267. /**
  49268. * An event triggered after the texture clear
  49269. * @type {BABYLON.Observable}
  49270. */
  49271. _this.onClearObservable = new BABYLON.Observable();
  49272. _this._currentRefreshId = -1;
  49273. _this._refreshRate = 1;
  49274. _this._samples = 1;
  49275. scene = _this.getScene();
  49276. if (!scene) {
  49277. return _this;
  49278. }
  49279. _this.name = name;
  49280. _this.isRenderTarget = true;
  49281. _this._size = size;
  49282. _this._generateMipMaps = generateMipMaps ? true : false;
  49283. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49284. // Rendering groups
  49285. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49286. if (isMulti) {
  49287. return _this;
  49288. }
  49289. _this._renderTargetOptions = {
  49290. generateMipMaps: generateMipMaps,
  49291. type: type,
  49292. samplingMode: samplingMode,
  49293. generateDepthBuffer: generateDepthBuffer,
  49294. generateStencilBuffer: generateStencilBuffer
  49295. };
  49296. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49297. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49298. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49299. }
  49300. if (isCube) {
  49301. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  49302. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49303. _this._textureMatrix = BABYLON.Matrix.Identity();
  49304. }
  49305. else {
  49306. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  49307. }
  49308. return _this;
  49309. }
  49310. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49311. get: function () {
  49312. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49313. },
  49314. enumerable: true,
  49315. configurable: true
  49316. });
  49317. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49318. get: function () {
  49319. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49320. },
  49321. enumerable: true,
  49322. configurable: true
  49323. });
  49324. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49325. get: function () {
  49326. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49327. },
  49328. enumerable: true,
  49329. configurable: true
  49330. });
  49331. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49332. set: function (callback) {
  49333. if (this._onAfterUnbindObserver) {
  49334. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49335. }
  49336. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49337. },
  49338. enumerable: true,
  49339. configurable: true
  49340. });
  49341. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49342. set: function (callback) {
  49343. if (this._onBeforeRenderObserver) {
  49344. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49345. }
  49346. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49347. },
  49348. enumerable: true,
  49349. configurable: true
  49350. });
  49351. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49352. set: function (callback) {
  49353. if (this._onAfterRenderObserver) {
  49354. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49355. }
  49356. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49357. },
  49358. enumerable: true,
  49359. configurable: true
  49360. });
  49361. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49362. set: function (callback) {
  49363. if (this._onClearObserver) {
  49364. this.onClearObservable.remove(this._onClearObserver);
  49365. }
  49366. this._onClearObserver = this.onClearObservable.add(callback);
  49367. },
  49368. enumerable: true,
  49369. configurable: true
  49370. });
  49371. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49372. get: function () {
  49373. return this._renderTargetOptions;
  49374. },
  49375. enumerable: true,
  49376. configurable: true
  49377. });
  49378. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49379. get: function () {
  49380. return this._samples;
  49381. },
  49382. set: function (value) {
  49383. if (this._samples === value) {
  49384. return;
  49385. }
  49386. var scene = this.getScene();
  49387. if (!scene) {
  49388. return;
  49389. }
  49390. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49391. },
  49392. enumerable: true,
  49393. configurable: true
  49394. });
  49395. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49396. this._currentRefreshId = -1;
  49397. };
  49398. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49399. get: function () {
  49400. return this._refreshRate;
  49401. },
  49402. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49403. set: function (value) {
  49404. this._refreshRate = value;
  49405. this.resetRefreshCounter();
  49406. },
  49407. enumerable: true,
  49408. configurable: true
  49409. });
  49410. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49411. if (!this._postProcessManager) {
  49412. var scene = this.getScene();
  49413. if (!scene) {
  49414. return;
  49415. }
  49416. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49417. this._postProcesses = new Array();
  49418. }
  49419. this._postProcesses.push(postProcess);
  49420. this._postProcesses[0].autoClear = false;
  49421. };
  49422. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49423. if (!this._postProcesses) {
  49424. return;
  49425. }
  49426. if (dispose) {
  49427. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49428. var postProcess = _a[_i];
  49429. postProcess.dispose();
  49430. }
  49431. }
  49432. this._postProcesses = [];
  49433. };
  49434. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49435. if (!this._postProcesses) {
  49436. return;
  49437. }
  49438. var index = this._postProcesses.indexOf(postProcess);
  49439. if (index === -1) {
  49440. return;
  49441. }
  49442. this._postProcesses.splice(index, 1);
  49443. if (this._postProcesses.length > 0) {
  49444. this._postProcesses[0].autoClear = false;
  49445. }
  49446. };
  49447. RenderTargetTexture.prototype._shouldRender = function () {
  49448. if (this._currentRefreshId === -1) {
  49449. this._currentRefreshId = 1;
  49450. return true;
  49451. }
  49452. if (this.refreshRate === this._currentRefreshId) {
  49453. this._currentRefreshId = 1;
  49454. return true;
  49455. }
  49456. this._currentRefreshId++;
  49457. return false;
  49458. };
  49459. RenderTargetTexture.prototype.getRenderSize = function () {
  49460. return this._size;
  49461. };
  49462. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49463. get: function () {
  49464. return true;
  49465. },
  49466. enumerable: true,
  49467. configurable: true
  49468. });
  49469. RenderTargetTexture.prototype.scale = function (ratio) {
  49470. var newSize = this._size * ratio;
  49471. this.resize(newSize);
  49472. };
  49473. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49474. if (this.isCube) {
  49475. return this._textureMatrix;
  49476. }
  49477. return _super.prototype.getReflectionTextureMatrix.call(this);
  49478. };
  49479. RenderTargetTexture.prototype.resize = function (size) {
  49480. this.releaseInternalTexture();
  49481. var scene = this.getScene();
  49482. if (!scene) {
  49483. return;
  49484. }
  49485. if (this.isCube) {
  49486. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49487. }
  49488. else {
  49489. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49490. }
  49491. this._size = size;
  49492. };
  49493. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49494. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49495. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49496. var scene = this.getScene();
  49497. if (!scene) {
  49498. return;
  49499. }
  49500. var engine = scene.getEngine();
  49501. if (this.useCameraPostProcesses !== undefined) {
  49502. useCameraPostProcess = this.useCameraPostProcesses;
  49503. }
  49504. if (this._waitingRenderList) {
  49505. this.renderList = [];
  49506. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49507. var id = this._waitingRenderList[index];
  49508. var mesh_1 = scene.getMeshByID(id);
  49509. if (mesh_1) {
  49510. this.renderList.push(mesh_1);
  49511. }
  49512. }
  49513. delete this._waitingRenderList;
  49514. }
  49515. // Is predicate defined?
  49516. if (this.renderListPredicate) {
  49517. if (this.renderList) {
  49518. this.renderList.splice(0); // Clear previous renderList
  49519. }
  49520. else {
  49521. this.renderList = [];
  49522. }
  49523. var scene = this.getScene();
  49524. if (!scene) {
  49525. return;
  49526. }
  49527. var sceneMeshes = scene.meshes;
  49528. for (var index = 0; index < sceneMeshes.length; index++) {
  49529. var mesh = sceneMeshes[index];
  49530. if (this.renderListPredicate(mesh)) {
  49531. this.renderList.push(mesh);
  49532. }
  49533. }
  49534. }
  49535. this.onBeforeBindObservable.notifyObservers(this);
  49536. // Set custom projection.
  49537. // Needs to be before binding to prevent changing the aspect ratio.
  49538. var camera;
  49539. if (this.activeCamera) {
  49540. camera = this.activeCamera;
  49541. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49542. if (this.activeCamera !== scene.activeCamera) {
  49543. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49544. }
  49545. }
  49546. else {
  49547. camera = scene.activeCamera;
  49548. if (camera) {
  49549. engine.setViewport(camera.viewport, this._size, this._size);
  49550. }
  49551. }
  49552. // Prepare renderingManager
  49553. this._renderingManager.reset();
  49554. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49555. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49556. var sceneRenderId = scene.getRenderId();
  49557. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49558. var mesh = currentRenderList[meshIndex];
  49559. if (mesh) {
  49560. if (!mesh.isReady()) {
  49561. // Reset _currentRefreshId
  49562. this.resetRefreshCounter();
  49563. continue;
  49564. }
  49565. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49566. var isMasked = void 0;
  49567. if (!this.renderList && camera) {
  49568. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49569. }
  49570. else {
  49571. isMasked = false;
  49572. }
  49573. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49574. mesh._activate(sceneRenderId);
  49575. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49576. var subMesh = mesh.subMeshes[subIndex];
  49577. scene._activeIndices.addCount(subMesh.indexCount, false);
  49578. this._renderingManager.dispatch(subMesh);
  49579. }
  49580. }
  49581. }
  49582. }
  49583. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49584. var particleSystem = scene.particleSystems[particleIndex];
  49585. var emitter = particleSystem.emitter;
  49586. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49587. continue;
  49588. }
  49589. if (currentRenderList.indexOf(emitter) >= 0) {
  49590. this._renderingManager.dispatchParticles(particleSystem);
  49591. }
  49592. }
  49593. if (this.isCube) {
  49594. for (var face = 0; face < 6; face++) {
  49595. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49596. scene.incrementRenderId();
  49597. scene.resetCachedMaterial();
  49598. }
  49599. }
  49600. else {
  49601. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49602. }
  49603. this.onAfterUnbindObservable.notifyObservers(this);
  49604. if (scene.activeCamera) {
  49605. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49606. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49607. }
  49608. engine.setViewport(scene.activeCamera.viewport);
  49609. }
  49610. scene.resetCachedMaterial();
  49611. };
  49612. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49613. var _this = this;
  49614. var scene = this.getScene();
  49615. if (!scene) {
  49616. return;
  49617. }
  49618. var engine = scene.getEngine();
  49619. if (!this._texture) {
  49620. return;
  49621. }
  49622. // Bind
  49623. if (this._postProcessManager) {
  49624. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49625. }
  49626. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49627. if (this._texture) {
  49628. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49629. }
  49630. }
  49631. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49632. // Clear
  49633. if (this.onClearObservable.hasObservers()) {
  49634. this.onClearObservable.notifyObservers(engine);
  49635. }
  49636. else {
  49637. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49638. }
  49639. if (!this._doNotChangeAspectRatio) {
  49640. scene.updateTransformMatrix(true);
  49641. }
  49642. // Render
  49643. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49644. if (this._postProcessManager) {
  49645. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49646. }
  49647. else if (useCameraPostProcess) {
  49648. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49649. }
  49650. if (!this._doNotChangeAspectRatio) {
  49651. scene.updateTransformMatrix(true);
  49652. }
  49653. // Dump ?
  49654. if (dumpForDebug) {
  49655. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49656. }
  49657. // Unbind
  49658. if (!this.isCube || faceIndex === 5) {
  49659. if (this.isCube) {
  49660. if (faceIndex === 5) {
  49661. engine.generateMipMapsForCubemap(this._texture);
  49662. }
  49663. }
  49664. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49665. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49666. });
  49667. }
  49668. else {
  49669. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49670. }
  49671. };
  49672. /**
  49673. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49674. * This allowed control for front to back rendering or reversly depending of the special needs.
  49675. *
  49676. * @param renderingGroupId The rendering group id corresponding to its index
  49677. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49678. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49679. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49680. */
  49681. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49682. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49683. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49684. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49685. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49686. };
  49687. /**
  49688. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49689. *
  49690. * @param renderingGroupId The rendering group id corresponding to its index
  49691. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49692. */
  49693. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49694. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49695. };
  49696. RenderTargetTexture.prototype.clone = function () {
  49697. var textureSize = this.getSize();
  49698. 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);
  49699. // Base texture
  49700. newTexture.hasAlpha = this.hasAlpha;
  49701. newTexture.level = this.level;
  49702. // RenderTarget Texture
  49703. newTexture.coordinatesMode = this.coordinatesMode;
  49704. if (this.renderList) {
  49705. newTexture.renderList = this.renderList.slice(0);
  49706. }
  49707. return newTexture;
  49708. };
  49709. RenderTargetTexture.prototype.serialize = function () {
  49710. if (!this.name) {
  49711. return null;
  49712. }
  49713. var serializationObject = _super.prototype.serialize.call(this);
  49714. serializationObject.renderTargetSize = this.getRenderSize();
  49715. serializationObject.renderList = [];
  49716. if (this.renderList) {
  49717. for (var index = 0; index < this.renderList.length; index++) {
  49718. serializationObject.renderList.push(this.renderList[index].id);
  49719. }
  49720. }
  49721. return serializationObject;
  49722. };
  49723. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49724. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49725. var objBuffer = this.getInternalTexture();
  49726. var scene = this.getScene();
  49727. if (objBuffer && scene) {
  49728. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49729. }
  49730. };
  49731. RenderTargetTexture.prototype.dispose = function () {
  49732. if (this._postProcessManager) {
  49733. this._postProcessManager.dispose();
  49734. this._postProcessManager = null;
  49735. }
  49736. this.clearPostProcesses(true);
  49737. this.renderList = null;
  49738. // Remove from custom render targets
  49739. var scene = this.getScene();
  49740. if (!scene) {
  49741. return;
  49742. }
  49743. var index = scene.customRenderTargets.indexOf(this);
  49744. if (index >= 0) {
  49745. scene.customRenderTargets.splice(index, 1);
  49746. }
  49747. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49748. var camera = _a[_i];
  49749. index = camera.customRenderTargets.indexOf(this);
  49750. if (index >= 0) {
  49751. camera.customRenderTargets.splice(index, 1);
  49752. }
  49753. }
  49754. _super.prototype.dispose.call(this);
  49755. };
  49756. RenderTargetTexture.prototype._rebuild = function () {
  49757. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49758. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49759. }
  49760. if (this._postProcessManager) {
  49761. this._postProcessManager._rebuild();
  49762. }
  49763. };
  49764. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49765. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49766. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49767. return RenderTargetTexture;
  49768. }(BABYLON.Texture));
  49769. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49770. })(BABYLON || (BABYLON = {}));
  49771. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49772. var BABYLON;
  49773. (function (BABYLON) {
  49774. ;
  49775. var MultiRenderTarget = /** @class */ (function (_super) {
  49776. __extends(MultiRenderTarget, _super);
  49777. function MultiRenderTarget(name, size, count, scene, options) {
  49778. var _this = this;
  49779. options = options || {};
  49780. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49781. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49782. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49783. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49784. _this._engine = scene.getEngine();
  49785. if (!_this.isSupported) {
  49786. _this.dispose();
  49787. return;
  49788. }
  49789. var types = [];
  49790. var samplingModes = [];
  49791. for (var i = 0; i < count; i++) {
  49792. if (options.types && options.types[i]) {
  49793. types.push(options.types[i]);
  49794. }
  49795. else {
  49796. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49797. }
  49798. if (options.samplingModes && options.samplingModes[i]) {
  49799. samplingModes.push(options.samplingModes[i]);
  49800. }
  49801. else {
  49802. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49803. }
  49804. }
  49805. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49806. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49807. _this._count = count;
  49808. _this._size = size;
  49809. _this._multiRenderTargetOptions = {
  49810. samplingModes: samplingModes,
  49811. generateMipMaps: generateMipMaps,
  49812. generateDepthBuffer: generateDepthBuffer,
  49813. generateStencilBuffer: generateStencilBuffer,
  49814. generateDepthTexture: generateDepthTexture,
  49815. types: types,
  49816. textureCount: count
  49817. };
  49818. _this._createInternalTextures();
  49819. _this._createTextures();
  49820. return _this;
  49821. }
  49822. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49823. get: function () {
  49824. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49825. },
  49826. enumerable: true,
  49827. configurable: true
  49828. });
  49829. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49830. get: function () {
  49831. return this._textures;
  49832. },
  49833. enumerable: true,
  49834. configurable: true
  49835. });
  49836. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49837. get: function () {
  49838. return this._textures[this._textures.length - 1];
  49839. },
  49840. enumerable: true,
  49841. configurable: true
  49842. });
  49843. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49844. set: function (wrap) {
  49845. if (this._textures) {
  49846. for (var i = 0; i < this._textures.length; i++) {
  49847. this._textures[i].wrapU = wrap;
  49848. }
  49849. }
  49850. },
  49851. enumerable: true,
  49852. configurable: true
  49853. });
  49854. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49855. set: function (wrap) {
  49856. if (this._textures) {
  49857. for (var i = 0; i < this._textures.length; i++) {
  49858. this._textures[i].wrapV = wrap;
  49859. }
  49860. }
  49861. },
  49862. enumerable: true,
  49863. configurable: true
  49864. });
  49865. MultiRenderTarget.prototype._rebuild = function () {
  49866. this.releaseInternalTextures();
  49867. this._createInternalTextures();
  49868. for (var i = 0; i < this._internalTextures.length; i++) {
  49869. var texture = this._textures[i];
  49870. texture._texture = this._internalTextures[i];
  49871. }
  49872. // Keeps references to frame buffer and stencil/depth buffer
  49873. this._texture = this._internalTextures[0];
  49874. };
  49875. MultiRenderTarget.prototype._createInternalTextures = function () {
  49876. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49877. };
  49878. MultiRenderTarget.prototype._createTextures = function () {
  49879. this._textures = [];
  49880. for (var i = 0; i < this._internalTextures.length; i++) {
  49881. var texture = new BABYLON.Texture(null, this.getScene());
  49882. texture._texture = this._internalTextures[i];
  49883. this._textures.push(texture);
  49884. }
  49885. // Keeps references to frame buffer and stencil/depth buffer
  49886. this._texture = this._internalTextures[0];
  49887. };
  49888. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49889. get: function () {
  49890. return this._samples;
  49891. },
  49892. set: function (value) {
  49893. if (this._samples === value) {
  49894. return;
  49895. }
  49896. for (var i = 0; i < this._internalTextures.length; i++) {
  49897. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49898. }
  49899. },
  49900. enumerable: true,
  49901. configurable: true
  49902. });
  49903. MultiRenderTarget.prototype.resize = function (size) {
  49904. this.releaseInternalTextures();
  49905. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49906. this._createInternalTextures();
  49907. };
  49908. MultiRenderTarget.prototype.dispose = function () {
  49909. this.releaseInternalTextures();
  49910. _super.prototype.dispose.call(this);
  49911. };
  49912. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49913. if (!this._internalTextures) {
  49914. return;
  49915. }
  49916. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49917. if (this._internalTextures[i] !== undefined) {
  49918. this._internalTextures[i].dispose();
  49919. this._internalTextures.splice(i, 1);
  49920. }
  49921. }
  49922. };
  49923. return MultiRenderTarget;
  49924. }(BABYLON.RenderTargetTexture));
  49925. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49926. })(BABYLON || (BABYLON = {}));
  49927. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49928. var BABYLON;
  49929. (function (BABYLON) {
  49930. var MirrorTexture = /** @class */ (function (_super) {
  49931. __extends(MirrorTexture, _super);
  49932. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49933. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49934. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49935. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49936. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49937. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49938. _this._transformMatrix = BABYLON.Matrix.Zero();
  49939. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49940. _this._blurKernelX = 0;
  49941. _this._blurKernelY = 0;
  49942. _this._blurRatio = 1.0;
  49943. _this.ignoreCameraViewport = true;
  49944. _this.onBeforeRenderObservable.add(function () {
  49945. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49946. _this._savedViewMatrix = scene.getViewMatrix();
  49947. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49948. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49949. scene.clipPlane = _this.mirrorPlane;
  49950. scene.getEngine().cullBackFaces = false;
  49951. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49952. });
  49953. _this.onAfterRenderObservable.add(function () {
  49954. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49955. scene.getEngine().cullBackFaces = true;
  49956. scene._mirroredCameraPosition = null;
  49957. delete scene.clipPlane;
  49958. });
  49959. return _this;
  49960. }
  49961. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49962. get: function () {
  49963. return this._blurRatio;
  49964. },
  49965. set: function (value) {
  49966. if (this._blurRatio === value) {
  49967. return;
  49968. }
  49969. this._blurRatio = value;
  49970. this._preparePostProcesses();
  49971. },
  49972. enumerable: true,
  49973. configurable: true
  49974. });
  49975. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49976. set: function (value) {
  49977. this.blurKernelX = value;
  49978. this.blurKernelY = value;
  49979. },
  49980. enumerable: true,
  49981. configurable: true
  49982. });
  49983. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49984. get: function () {
  49985. return this._blurKernelX;
  49986. },
  49987. set: function (value) {
  49988. if (this._blurKernelX === value) {
  49989. return;
  49990. }
  49991. this._blurKernelX = value;
  49992. this._preparePostProcesses();
  49993. },
  49994. enumerable: true,
  49995. configurable: true
  49996. });
  49997. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49998. get: function () {
  49999. return this._blurKernelY;
  50000. },
  50001. set: function (value) {
  50002. if (this._blurKernelY === value) {
  50003. return;
  50004. }
  50005. this._blurKernelY = value;
  50006. this._preparePostProcesses();
  50007. },
  50008. enumerable: true,
  50009. configurable: true
  50010. });
  50011. MirrorTexture.prototype._preparePostProcesses = function () {
  50012. this.clearPostProcesses(true);
  50013. if (this._blurKernelX && this._blurKernelY) {
  50014. var engine = this.getScene().getEngine();
  50015. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50016. 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);
  50017. this._blurX.autoClear = false;
  50018. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50019. this._blurX.outputTexture = this._texture;
  50020. }
  50021. else {
  50022. this._blurX.alwaysForcePOT = true;
  50023. }
  50024. 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);
  50025. this._blurY.autoClear = false;
  50026. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50027. this.addPostProcess(this._blurX);
  50028. this.addPostProcess(this._blurY);
  50029. }
  50030. };
  50031. MirrorTexture.prototype.clone = function () {
  50032. var scene = this.getScene();
  50033. if (!scene) {
  50034. return this;
  50035. }
  50036. var textureSize = this.getSize();
  50037. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50038. // Base texture
  50039. newTexture.hasAlpha = this.hasAlpha;
  50040. newTexture.level = this.level;
  50041. // Mirror Texture
  50042. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50043. if (this.renderList) {
  50044. newTexture.renderList = this.renderList.slice(0);
  50045. }
  50046. return newTexture;
  50047. };
  50048. MirrorTexture.prototype.serialize = function () {
  50049. if (!this.name) {
  50050. return null;
  50051. }
  50052. var serializationObject = _super.prototype.serialize.call(this);
  50053. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50054. return serializationObject;
  50055. };
  50056. return MirrorTexture;
  50057. }(BABYLON.RenderTargetTexture));
  50058. BABYLON.MirrorTexture = MirrorTexture;
  50059. })(BABYLON || (BABYLON = {}));
  50060. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50061. var BABYLON;
  50062. (function (BABYLON) {
  50063. /**
  50064. * Creates a refraction texture used by refraction channel of the standard material.
  50065. * @param name the texture name
  50066. * @param size size of the underlying texture
  50067. * @param scene root scene
  50068. */
  50069. var RefractionTexture = /** @class */ (function (_super) {
  50070. __extends(RefractionTexture, _super);
  50071. function RefractionTexture(name, size, scene, generateMipMaps) {
  50072. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50073. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50074. _this.depth = 2.0;
  50075. _this.onBeforeRenderObservable.add(function () {
  50076. scene.clipPlane = _this.refractionPlane;
  50077. });
  50078. _this.onAfterRenderObservable.add(function () {
  50079. delete scene.clipPlane;
  50080. });
  50081. return _this;
  50082. }
  50083. RefractionTexture.prototype.clone = function () {
  50084. var scene = this.getScene();
  50085. if (!scene) {
  50086. return this;
  50087. }
  50088. var textureSize = this.getSize();
  50089. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50090. // Base texture
  50091. newTexture.hasAlpha = this.hasAlpha;
  50092. newTexture.level = this.level;
  50093. // Refraction Texture
  50094. newTexture.refractionPlane = this.refractionPlane.clone();
  50095. if (this.renderList) {
  50096. newTexture.renderList = this.renderList.slice(0);
  50097. }
  50098. newTexture.depth = this.depth;
  50099. return newTexture;
  50100. };
  50101. RefractionTexture.prototype.serialize = function () {
  50102. if (!this.name) {
  50103. return null;
  50104. }
  50105. var serializationObject = _super.prototype.serialize.call(this);
  50106. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50107. serializationObject.depth = this.depth;
  50108. return serializationObject;
  50109. };
  50110. return RefractionTexture;
  50111. }(BABYLON.RenderTargetTexture));
  50112. BABYLON.RefractionTexture = RefractionTexture;
  50113. })(BABYLON || (BABYLON = {}));
  50114. //# sourceMappingURL=babylon.refractionTexture.js.map
  50115. var BABYLON;
  50116. (function (BABYLON) {
  50117. var DynamicTexture = /** @class */ (function (_super) {
  50118. __extends(DynamicTexture, _super);
  50119. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50120. if (scene === void 0) { scene = null; }
  50121. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50122. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50123. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50124. _this.name = name;
  50125. _this._engine = _this.getScene().getEngine();
  50126. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50127. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50128. _this._generateMipMaps = generateMipMaps;
  50129. if (options.getContext) {
  50130. _this._canvas = options;
  50131. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50132. }
  50133. else {
  50134. _this._canvas = document.createElement("canvas");
  50135. if (options.width) {
  50136. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50137. }
  50138. else {
  50139. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50140. }
  50141. }
  50142. var textureSize = _this.getSize();
  50143. _this._canvas.width = textureSize.width;
  50144. _this._canvas.height = textureSize.height;
  50145. _this._context = _this._canvas.getContext("2d");
  50146. return _this;
  50147. }
  50148. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50149. get: function () {
  50150. return true;
  50151. },
  50152. enumerable: true,
  50153. configurable: true
  50154. });
  50155. DynamicTexture.prototype._recreate = function (textureSize) {
  50156. this._canvas.width = textureSize.width;
  50157. this._canvas.height = textureSize.height;
  50158. this.releaseInternalTexture();
  50159. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50160. };
  50161. DynamicTexture.prototype.scale = function (ratio) {
  50162. var textureSize = this.getSize();
  50163. textureSize.width *= ratio;
  50164. textureSize.height *= ratio;
  50165. this._recreate(textureSize);
  50166. };
  50167. DynamicTexture.prototype.scaleTo = function (width, height) {
  50168. var textureSize = this.getSize();
  50169. textureSize.width = width;
  50170. textureSize.height = height;
  50171. this._recreate(textureSize);
  50172. };
  50173. DynamicTexture.prototype.getContext = function () {
  50174. return this._context;
  50175. };
  50176. DynamicTexture.prototype.clear = function () {
  50177. var size = this.getSize();
  50178. this._context.fillRect(0, 0, size.width, size.height);
  50179. };
  50180. DynamicTexture.prototype.update = function (invertY) {
  50181. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50182. };
  50183. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50184. if (update === void 0) { update = true; }
  50185. var size = this.getSize();
  50186. if (clearColor) {
  50187. this._context.fillStyle = clearColor;
  50188. this._context.fillRect(0, 0, size.width, size.height);
  50189. }
  50190. this._context.font = font;
  50191. if (x === null || x === undefined) {
  50192. var textSize = this._context.measureText(text);
  50193. x = (size.width - textSize.width) / 2;
  50194. }
  50195. if (y === null || y === undefined) {
  50196. var fontSize = parseInt((font.replace(/\D/g, '')));
  50197. ;
  50198. y = (size.height / 2) + (fontSize / 3.65);
  50199. }
  50200. this._context.fillStyle = color;
  50201. this._context.fillText(text, x, y);
  50202. if (update) {
  50203. this.update(invertY);
  50204. }
  50205. };
  50206. DynamicTexture.prototype.clone = function () {
  50207. var scene = this.getScene();
  50208. if (!scene) {
  50209. return this;
  50210. }
  50211. var textureSize = this.getSize();
  50212. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50213. // Base texture
  50214. newTexture.hasAlpha = this.hasAlpha;
  50215. newTexture.level = this.level;
  50216. // Dynamic Texture
  50217. newTexture.wrapU = this.wrapU;
  50218. newTexture.wrapV = this.wrapV;
  50219. return newTexture;
  50220. };
  50221. DynamicTexture.prototype._rebuild = function () {
  50222. this.update();
  50223. };
  50224. return DynamicTexture;
  50225. }(BABYLON.Texture));
  50226. BABYLON.DynamicTexture = DynamicTexture;
  50227. })(BABYLON || (BABYLON = {}));
  50228. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50229. var BABYLON;
  50230. (function (BABYLON) {
  50231. var VideoTexture = /** @class */ (function (_super) {
  50232. __extends(VideoTexture, _super);
  50233. /**
  50234. * Creates a video texture.
  50235. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50236. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50237. * @param {BABYLON.Scene} scene is obviously the current scene.
  50238. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50239. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50240. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50241. */
  50242. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50243. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50244. if (invertY === void 0) { invertY = false; }
  50245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50246. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50247. _this._autoLaunch = true;
  50248. var urls = null;
  50249. _this.name = name;
  50250. if (urlsOrVideo instanceof HTMLVideoElement) {
  50251. _this.video = urlsOrVideo;
  50252. }
  50253. else {
  50254. urls = urlsOrVideo;
  50255. _this.video = document.createElement("video");
  50256. _this.video.autoplay = false;
  50257. _this.video.loop = true;
  50258. }
  50259. _this._engine = _this.getScene().getEngine();
  50260. _this._generateMipMaps = generateMipMaps;
  50261. _this._samplingMode = samplingMode;
  50262. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50263. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50264. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50265. }
  50266. else {
  50267. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50268. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50269. _this._generateMipMaps = false;
  50270. }
  50271. if (urls) {
  50272. _this.video.addEventListener("canplay", function () {
  50273. _this._createTexture();
  50274. });
  50275. urls.forEach(function (url) {
  50276. var source = document.createElement("source");
  50277. source.src = url;
  50278. _this.video.appendChild(source);
  50279. });
  50280. }
  50281. else {
  50282. _this._createTexture();
  50283. }
  50284. _this._lastUpdate = BABYLON.Tools.Now;
  50285. return _this;
  50286. }
  50287. VideoTexture.prototype.__setTextureReady = function () {
  50288. if (this._texture) {
  50289. this._texture.isReady = true;
  50290. }
  50291. };
  50292. VideoTexture.prototype._createTexture = function () {
  50293. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50294. if (this._autoLaunch) {
  50295. this._autoLaunch = false;
  50296. this.video.play();
  50297. }
  50298. this._setTextureReady = this.__setTextureReady.bind(this);
  50299. this.video.addEventListener("playing", this._setTextureReady);
  50300. };
  50301. VideoTexture.prototype._rebuild = function () {
  50302. this.update();
  50303. };
  50304. VideoTexture.prototype.update = function () {
  50305. var now = BABYLON.Tools.Now;
  50306. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50307. return false;
  50308. }
  50309. this._lastUpdate = now;
  50310. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50311. return true;
  50312. };
  50313. VideoTexture.prototype.dispose = function () {
  50314. _super.prototype.dispose.call(this);
  50315. this.video.removeEventListener("playing", this._setTextureReady);
  50316. };
  50317. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50318. var video = document.createElement("video");
  50319. var constraintsDeviceId;
  50320. if (constraints && constraints.deviceId) {
  50321. constraintsDeviceId = {
  50322. exact: constraints.deviceId
  50323. };
  50324. }
  50325. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50326. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50327. if (navigator.getUserMedia) {
  50328. navigator.getUserMedia({
  50329. video: {
  50330. deviceId: constraintsDeviceId,
  50331. width: {
  50332. min: (constraints && constraints.minWidth) || 256,
  50333. max: (constraints && constraints.maxWidth) || 640
  50334. },
  50335. height: {
  50336. min: (constraints && constraints.minHeight) || 256,
  50337. max: (constraints && constraints.maxHeight) || 480
  50338. }
  50339. }
  50340. }, function (stream) {
  50341. if (video.mozSrcObject !== undefined) {
  50342. video.mozSrcObject = stream;
  50343. }
  50344. else {
  50345. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50346. }
  50347. video.play();
  50348. if (onReady) {
  50349. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50350. }
  50351. }, function (e) {
  50352. BABYLON.Tools.Error(e.name);
  50353. });
  50354. }
  50355. };
  50356. return VideoTexture;
  50357. }(BABYLON.Texture));
  50358. BABYLON.VideoTexture = VideoTexture;
  50359. })(BABYLON || (BABYLON = {}));
  50360. //# sourceMappingURL=babylon.videoTexture.js.map
  50361. var BABYLON;
  50362. (function (BABYLON) {
  50363. var RawTexture = /** @class */ (function (_super) {
  50364. __extends(RawTexture, _super);
  50365. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50367. if (invertY === void 0) { invertY = false; }
  50368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50369. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50370. _this.format = format;
  50371. _this._engine = scene.getEngine();
  50372. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50373. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50374. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50375. return _this;
  50376. }
  50377. RawTexture.prototype.update = function (data) {
  50378. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50379. };
  50380. // Statics
  50381. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50382. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50383. if (invertY === void 0) { invertY = false; }
  50384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50385. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50386. };
  50387. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50388. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50389. if (invertY === void 0) { invertY = false; }
  50390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50391. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50392. };
  50393. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50394. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50395. if (invertY === void 0) { invertY = false; }
  50396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50397. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50398. };
  50399. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50400. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50401. if (invertY === void 0) { invertY = false; }
  50402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50403. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50404. };
  50405. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50406. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50407. if (invertY === void 0) { invertY = false; }
  50408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50409. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50410. };
  50411. return RawTexture;
  50412. }(BABYLON.Texture));
  50413. BABYLON.RawTexture = RawTexture;
  50414. })(BABYLON || (BABYLON = {}));
  50415. //# sourceMappingURL=babylon.rawTexture.js.map
  50416. var BABYLON;
  50417. (function (BABYLON) {
  50418. var PostProcess = /** @class */ (function () {
  50419. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50421. if (defines === void 0) { defines = null; }
  50422. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50423. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50424. if (blockCompilation === void 0) { blockCompilation = false; }
  50425. this.name = name;
  50426. this.width = -1;
  50427. this.height = -1;
  50428. this.autoClear = true;
  50429. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50430. /*
  50431. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50432. Can only be used on a single postprocess or on the last one of a chain.
  50433. */
  50434. this.enablePixelPerfectMode = false;
  50435. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50436. this.alwaysForcePOT = false;
  50437. this.samples = 1;
  50438. this.adaptScaleToCurrentViewport = false;
  50439. this._reusable = false;
  50440. this._textures = new BABYLON.SmartArray(2);
  50441. this._currentRenderTextureInd = 0;
  50442. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50443. this._texelSize = BABYLON.Vector2.Zero();
  50444. // Events
  50445. /**
  50446. * An event triggered when the postprocess is activated.
  50447. * @type {BABYLON.Observable}
  50448. */
  50449. this.onActivateObservable = new BABYLON.Observable();
  50450. /**
  50451. * An event triggered when the postprocess changes its size.
  50452. * @type {BABYLON.Observable}
  50453. */
  50454. this.onSizeChangedObservable = new BABYLON.Observable();
  50455. /**
  50456. * An event triggered when the postprocess applies its effect.
  50457. * @type {BABYLON.Observable}
  50458. */
  50459. this.onApplyObservable = new BABYLON.Observable();
  50460. /**
  50461. * An event triggered before rendering the postprocess
  50462. * @type {BABYLON.Observable}
  50463. */
  50464. this.onBeforeRenderObservable = new BABYLON.Observable();
  50465. /**
  50466. * An event triggered after rendering the postprocess
  50467. * @type {BABYLON.Observable}
  50468. */
  50469. this.onAfterRenderObservable = new BABYLON.Observable();
  50470. if (camera != null) {
  50471. this._camera = camera;
  50472. this._scene = camera.getScene();
  50473. camera.attachPostProcess(this);
  50474. this._engine = this._scene.getEngine();
  50475. this._scene.postProcesses.push(this);
  50476. }
  50477. else if (engine) {
  50478. this._engine = engine;
  50479. this._engine.postProcesses.push(this);
  50480. }
  50481. this._options = options;
  50482. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50483. this._reusable = reusable || false;
  50484. this._textureType = textureType;
  50485. this._samplers = samplers || [];
  50486. this._samplers.push("textureSampler");
  50487. this._fragmentUrl = fragmentUrl;
  50488. this._vertexUrl = vertexUrl;
  50489. this._parameters = parameters || [];
  50490. this._parameters.push("scale");
  50491. this._indexParameters = indexParameters;
  50492. if (!blockCompilation) {
  50493. this.updateEffect(defines);
  50494. }
  50495. }
  50496. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50497. set: function (callback) {
  50498. if (this._onActivateObserver) {
  50499. this.onActivateObservable.remove(this._onActivateObserver);
  50500. }
  50501. if (callback) {
  50502. this._onActivateObserver = this.onActivateObservable.add(callback);
  50503. }
  50504. },
  50505. enumerable: true,
  50506. configurable: true
  50507. });
  50508. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50509. set: function (callback) {
  50510. if (this._onSizeChangedObserver) {
  50511. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50512. }
  50513. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50514. },
  50515. enumerable: true,
  50516. configurable: true
  50517. });
  50518. Object.defineProperty(PostProcess.prototype, "onApply", {
  50519. set: function (callback) {
  50520. if (this._onApplyObserver) {
  50521. this.onApplyObservable.remove(this._onApplyObserver);
  50522. }
  50523. this._onApplyObserver = this.onApplyObservable.add(callback);
  50524. },
  50525. enumerable: true,
  50526. configurable: true
  50527. });
  50528. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50529. set: function (callback) {
  50530. if (this._onBeforeRenderObserver) {
  50531. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50532. }
  50533. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50534. },
  50535. enumerable: true,
  50536. configurable: true
  50537. });
  50538. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50539. set: function (callback) {
  50540. if (this._onAfterRenderObserver) {
  50541. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50542. }
  50543. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50544. },
  50545. enumerable: true,
  50546. configurable: true
  50547. });
  50548. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50549. get: function () {
  50550. return this._textures.data[this._currentRenderTextureInd];
  50551. },
  50552. set: function (value) {
  50553. this._forcedOutputTexture = value;
  50554. },
  50555. enumerable: true,
  50556. configurable: true
  50557. });
  50558. PostProcess.prototype.getCamera = function () {
  50559. return this._camera;
  50560. };
  50561. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50562. get: function () {
  50563. if (this._shareOutputWithPostProcess) {
  50564. return this._shareOutputWithPostProcess.texelSize;
  50565. }
  50566. if (this._forcedOutputTexture) {
  50567. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50568. }
  50569. return this._texelSize;
  50570. },
  50571. enumerable: true,
  50572. configurable: true
  50573. });
  50574. PostProcess.prototype.getEngine = function () {
  50575. return this._engine;
  50576. };
  50577. PostProcess.prototype.getEffect = function () {
  50578. return this._effect;
  50579. };
  50580. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50581. this._disposeTextures();
  50582. this._shareOutputWithPostProcess = postProcess;
  50583. return this;
  50584. };
  50585. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50586. if (defines === void 0) { defines = null; }
  50587. if (uniforms === void 0) { uniforms = null; }
  50588. if (samplers === void 0) { samplers = null; }
  50589. 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);
  50590. };
  50591. PostProcess.prototype.isReusable = function () {
  50592. return this._reusable;
  50593. };
  50594. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50595. PostProcess.prototype.markTextureDirty = function () {
  50596. this.width = -1;
  50597. };
  50598. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50599. var _this = this;
  50600. if (sourceTexture === void 0) { sourceTexture = null; }
  50601. camera = camera || this._camera;
  50602. var scene = camera.getScene();
  50603. var engine = scene.getEngine();
  50604. var maxSize = engine.getCaps().maxTextureSize;
  50605. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50606. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50607. var desiredWidth = (this._options.width || requiredWidth);
  50608. var desiredHeight = this._options.height || requiredHeight;
  50609. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50610. if (this.adaptScaleToCurrentViewport) {
  50611. var currentViewport = engine.currentViewport;
  50612. if (currentViewport) {
  50613. desiredWidth *= currentViewport.width;
  50614. desiredHeight *= currentViewport.height;
  50615. }
  50616. }
  50617. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50618. if (!this._options.width) {
  50619. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50620. }
  50621. if (!this._options.height) {
  50622. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50623. }
  50624. }
  50625. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50626. if (this._textures.length > 0) {
  50627. for (var i = 0; i < this._textures.length; i++) {
  50628. this._engine._releaseTexture(this._textures.data[i]);
  50629. }
  50630. this._textures.reset();
  50631. }
  50632. this.width = desiredWidth;
  50633. this.height = desiredHeight;
  50634. var textureSize = { width: this.width, height: this.height };
  50635. var textureOptions = {
  50636. generateMipMaps: false,
  50637. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50638. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50639. samplingMode: this.renderTargetSamplingMode,
  50640. type: this._textureType
  50641. };
  50642. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50643. if (this._reusable) {
  50644. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50645. }
  50646. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50647. this.onSizeChangedObservable.notifyObservers(this);
  50648. }
  50649. this._textures.forEach(function (texture) {
  50650. if (texture.samples !== _this.samples) {
  50651. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50652. }
  50653. });
  50654. }
  50655. var target;
  50656. if (this._shareOutputWithPostProcess) {
  50657. target = this._shareOutputWithPostProcess.outputTexture;
  50658. }
  50659. else if (this._forcedOutputTexture) {
  50660. target = this._forcedOutputTexture;
  50661. this.width = this._forcedOutputTexture.width;
  50662. this.height = this._forcedOutputTexture.height;
  50663. }
  50664. else {
  50665. target = this.outputTexture;
  50666. }
  50667. if (this.enablePixelPerfectMode) {
  50668. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50669. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50670. }
  50671. else {
  50672. this._scaleRatio.copyFromFloats(1, 1);
  50673. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50674. }
  50675. this.onActivateObservable.notifyObservers(camera);
  50676. // Clear
  50677. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50678. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50679. }
  50680. if (this._reusable) {
  50681. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50682. }
  50683. };
  50684. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50685. get: function () {
  50686. return this._effect.isSupported;
  50687. },
  50688. enumerable: true,
  50689. configurable: true
  50690. });
  50691. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50692. get: function () {
  50693. if (this._shareOutputWithPostProcess) {
  50694. return this._shareOutputWithPostProcess.aspectRatio;
  50695. }
  50696. if (this._forcedOutputTexture) {
  50697. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50698. }
  50699. return this.width / this.height;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. PostProcess.prototype.apply = function () {
  50705. // Check
  50706. if (!this._effect || !this._effect.isReady())
  50707. return null;
  50708. // States
  50709. this._engine.enableEffect(this._effect);
  50710. this._engine.setState(false);
  50711. this._engine.setDepthBuffer(false);
  50712. this._engine.setDepthWrite(false);
  50713. // Alpha
  50714. this._engine.setAlphaMode(this.alphaMode);
  50715. if (this.alphaConstants) {
  50716. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50717. }
  50718. // Texture
  50719. var source;
  50720. if (this._shareOutputWithPostProcess) {
  50721. source = this._shareOutputWithPostProcess.outputTexture;
  50722. }
  50723. else if (this._forcedOutputTexture) {
  50724. source = this._forcedOutputTexture;
  50725. }
  50726. else {
  50727. source = this.outputTexture;
  50728. }
  50729. this._effect._bindTexture("textureSampler", source);
  50730. // Parameters
  50731. this._effect.setVector2("scale", this._scaleRatio);
  50732. this.onApplyObservable.notifyObservers(this._effect);
  50733. return this._effect;
  50734. };
  50735. PostProcess.prototype._disposeTextures = function () {
  50736. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50737. return;
  50738. }
  50739. if (this._textures.length > 0) {
  50740. for (var i = 0; i < this._textures.length; i++) {
  50741. this._engine._releaseTexture(this._textures.data[i]);
  50742. }
  50743. }
  50744. this._textures.dispose();
  50745. };
  50746. PostProcess.prototype.dispose = function (camera) {
  50747. camera = camera || this._camera;
  50748. this._disposeTextures();
  50749. if (this._scene) {
  50750. var index_1 = this._scene.postProcesses.indexOf(this);
  50751. if (index_1 !== -1) {
  50752. this._scene.postProcesses.splice(index_1, 1);
  50753. }
  50754. }
  50755. else {
  50756. var index_2 = this._engine.postProcesses.indexOf(this);
  50757. if (index_2 !== -1) {
  50758. this._engine.postProcesses.splice(index_2, 1);
  50759. }
  50760. }
  50761. if (!camera) {
  50762. return;
  50763. }
  50764. camera.detachPostProcess(this);
  50765. var index = camera._postProcesses.indexOf(this);
  50766. if (index === 0 && camera._postProcesses.length > 0) {
  50767. this._camera._postProcesses[0].markTextureDirty();
  50768. }
  50769. this.onActivateObservable.clear();
  50770. this.onAfterRenderObservable.clear();
  50771. this.onApplyObservable.clear();
  50772. this.onBeforeRenderObservable.clear();
  50773. this.onSizeChangedObservable.clear();
  50774. };
  50775. return PostProcess;
  50776. }());
  50777. BABYLON.PostProcess = PostProcess;
  50778. })(BABYLON || (BABYLON = {}));
  50779. //# sourceMappingURL=babylon.postProcess.js.map
  50780. var BABYLON;
  50781. (function (BABYLON) {
  50782. var PassPostProcess = /** @class */ (function (_super) {
  50783. __extends(PassPostProcess, _super);
  50784. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50785. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50786. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50787. }
  50788. return PassPostProcess;
  50789. }(BABYLON.PostProcess));
  50790. BABYLON.PassPostProcess = PassPostProcess;
  50791. })(BABYLON || (BABYLON = {}));
  50792. //# sourceMappingURL=babylon.passPostProcess.js.map
  50793. var BABYLON;
  50794. (function (BABYLON) {
  50795. var ShadowGenerator = /** @class */ (function () {
  50796. /**
  50797. * Creates a ShadowGenerator object.
  50798. * A ShadowGenerator is the required tool to use the shadows.
  50799. * Each light casting shadows needs to use its own ShadowGenerator.
  50800. * Required parameters :
  50801. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50802. * - `light`: the light object generating the shadows.
  50803. * - `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.
  50804. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50805. */
  50806. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50807. // Members
  50808. this._bias = 0.00005;
  50809. this._blurBoxOffset = 1;
  50810. this._blurScale = 2;
  50811. this._blurKernel = 1;
  50812. this._useKernelBlur = false;
  50813. this._filter = ShadowGenerator.FILTER_NONE;
  50814. this._darkness = 0;
  50815. this._transparencyShadow = false;
  50816. /**
  50817. * Controls the extent to which the shadows fade out at the edge of the frustum
  50818. * Used only by directionals and spots
  50819. */
  50820. this.frustumEdgeFalloff = 0;
  50821. this.forceBackFacesOnly = false;
  50822. this._lightDirection = BABYLON.Vector3.Zero();
  50823. this._viewMatrix = BABYLON.Matrix.Zero();
  50824. this._projectionMatrix = BABYLON.Matrix.Zero();
  50825. this._transformMatrix = BABYLON.Matrix.Zero();
  50826. this._currentFaceIndex = 0;
  50827. this._currentFaceIndexCache = 0;
  50828. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50829. this._mapSize = mapSize;
  50830. this._light = light;
  50831. this._scene = light.getScene();
  50832. light._shadowGenerator = this;
  50833. // Texture type fallback from float to int if not supported.
  50834. var caps = this._scene.getEngine().getCaps();
  50835. if (!useFullFloatFirst) {
  50836. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50837. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50838. }
  50839. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50840. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50841. }
  50842. else {
  50843. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50844. }
  50845. }
  50846. else {
  50847. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50848. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50849. }
  50850. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50851. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50852. }
  50853. else {
  50854. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50855. }
  50856. }
  50857. this._initializeGenerator();
  50858. }
  50859. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50860. // Static
  50861. get: function () {
  50862. return ShadowGenerator._FILTER_NONE;
  50863. },
  50864. enumerable: true,
  50865. configurable: true
  50866. });
  50867. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50868. get: function () {
  50869. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50870. },
  50871. enumerable: true,
  50872. configurable: true
  50873. });
  50874. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50875. get: function () {
  50876. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50877. },
  50878. enumerable: true,
  50879. configurable: true
  50880. });
  50881. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50882. get: function () {
  50883. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50884. },
  50885. enumerable: true,
  50886. configurable: true
  50887. });
  50888. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50889. get: function () {
  50890. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50891. },
  50892. enumerable: true,
  50893. configurable: true
  50894. });
  50895. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50896. get: function () {
  50897. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50903. get: function () {
  50904. return this._bias;
  50905. },
  50906. set: function (bias) {
  50907. this._bias = bias;
  50908. },
  50909. enumerable: true,
  50910. configurable: true
  50911. });
  50912. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50913. get: function () {
  50914. return this._blurBoxOffset;
  50915. },
  50916. set: function (value) {
  50917. if (this._blurBoxOffset === value) {
  50918. return;
  50919. }
  50920. this._blurBoxOffset = value;
  50921. this._disposeBlurPostProcesses();
  50922. },
  50923. enumerable: true,
  50924. configurable: true
  50925. });
  50926. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50927. get: function () {
  50928. return this._blurScale;
  50929. },
  50930. set: function (value) {
  50931. if (this._blurScale === value) {
  50932. return;
  50933. }
  50934. this._blurScale = value;
  50935. this._disposeBlurPostProcesses();
  50936. },
  50937. enumerable: true,
  50938. configurable: true
  50939. });
  50940. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50941. get: function () {
  50942. return this._blurKernel;
  50943. },
  50944. set: function (value) {
  50945. if (this._blurKernel === value) {
  50946. return;
  50947. }
  50948. this._blurKernel = value;
  50949. this._disposeBlurPostProcesses();
  50950. },
  50951. enumerable: true,
  50952. configurable: true
  50953. });
  50954. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50955. get: function () {
  50956. return this._useKernelBlur;
  50957. },
  50958. set: function (value) {
  50959. if (this._useKernelBlur === value) {
  50960. return;
  50961. }
  50962. this._useKernelBlur = value;
  50963. this._disposeBlurPostProcesses();
  50964. },
  50965. enumerable: true,
  50966. configurable: true
  50967. });
  50968. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50969. get: function () {
  50970. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50971. },
  50972. set: function (value) {
  50973. this._depthScale = value;
  50974. },
  50975. enumerable: true,
  50976. configurable: true
  50977. });
  50978. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50979. get: function () {
  50980. return this._filter;
  50981. },
  50982. set: function (value) {
  50983. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50984. if (this._light.needCube()) {
  50985. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50986. this.useExponentialShadowMap = true;
  50987. return;
  50988. }
  50989. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50990. this.useCloseExponentialShadowMap = true;
  50991. return;
  50992. }
  50993. }
  50994. if (this._filter === value) {
  50995. return;
  50996. }
  50997. this._filter = value;
  50998. this._disposeBlurPostProcesses();
  50999. this._applyFilterValues();
  51000. this._light._markMeshesAsLightDirty();
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51006. get: function () {
  51007. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51008. },
  51009. set: function (value) {
  51010. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51011. return;
  51012. }
  51013. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51014. },
  51015. enumerable: true,
  51016. configurable: true
  51017. });
  51018. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51019. get: function () {
  51020. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51021. return this.useExponentialShadowMap;
  51022. },
  51023. set: function (value) {
  51024. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51025. this.useExponentialShadowMap = value;
  51026. },
  51027. enumerable: true,
  51028. configurable: true
  51029. });
  51030. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51031. get: function () {
  51032. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51033. return this.useBlurExponentialShadowMap;
  51034. },
  51035. set: function (value) {
  51036. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51037. this.useBlurExponentialShadowMap = value;
  51038. },
  51039. enumerable: true,
  51040. configurable: true
  51041. });
  51042. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51043. get: function () {
  51044. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51045. },
  51046. set: function (value) {
  51047. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51048. return;
  51049. }
  51050. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51051. },
  51052. enumerable: true,
  51053. configurable: true
  51054. });
  51055. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51056. get: function () {
  51057. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51058. },
  51059. set: function (value) {
  51060. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51061. return;
  51062. }
  51063. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51064. },
  51065. enumerable: true,
  51066. configurable: true
  51067. });
  51068. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51069. get: function () {
  51070. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51071. },
  51072. set: function (value) {
  51073. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51074. return;
  51075. }
  51076. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51082. get: function () {
  51083. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51084. },
  51085. set: function (value) {
  51086. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51087. return;
  51088. }
  51089. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51090. },
  51091. enumerable: true,
  51092. configurable: true
  51093. });
  51094. /**
  51095. * Returns the darkness value (float).
  51096. */
  51097. ShadowGenerator.prototype.getDarkness = function () {
  51098. return this._darkness;
  51099. };
  51100. /**
  51101. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51102. * Returns the ShadowGenerator.
  51103. */
  51104. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51105. if (darkness >= 1.0)
  51106. this._darkness = 1.0;
  51107. else if (darkness <= 0.0)
  51108. this._darkness = 0.0;
  51109. else
  51110. this._darkness = darkness;
  51111. return this;
  51112. };
  51113. /**
  51114. * Sets the ability to have transparent shadow (boolean).
  51115. * Returns the ShadowGenerator.
  51116. */
  51117. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51118. this._transparencyShadow = hasShadow;
  51119. return this;
  51120. };
  51121. /**
  51122. * Returns a RenderTargetTexture object : the shadow map texture.
  51123. */
  51124. ShadowGenerator.prototype.getShadowMap = function () {
  51125. return this._shadowMap;
  51126. };
  51127. /**
  51128. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51129. */
  51130. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51131. if (this._shadowMap2) {
  51132. return this._shadowMap2;
  51133. }
  51134. return this._shadowMap;
  51135. };
  51136. /**
  51137. * Helper function to add a mesh and its descendants to the list of shadow casters
  51138. * @param mesh Mesh to add
  51139. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51140. */
  51141. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51142. if (includeDescendants === void 0) { includeDescendants = true; }
  51143. if (!this._shadowMap) {
  51144. return this;
  51145. }
  51146. if (!this._shadowMap.renderList) {
  51147. this._shadowMap.renderList = [];
  51148. }
  51149. this._shadowMap.renderList.push(mesh);
  51150. if (includeDescendants) {
  51151. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51152. }
  51153. return this;
  51154. var _a;
  51155. };
  51156. /**
  51157. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51158. * @param mesh Mesh to remove
  51159. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51160. */
  51161. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51162. if (includeDescendants === void 0) { includeDescendants = true; }
  51163. if (!this._shadowMap || !this._shadowMap.renderList) {
  51164. return this;
  51165. }
  51166. var index = this._shadowMap.renderList.indexOf(mesh);
  51167. if (index !== -1) {
  51168. this._shadowMap.renderList.splice(index, 1);
  51169. }
  51170. if (includeDescendants) {
  51171. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51172. var child = _a[_i];
  51173. this.removeShadowCaster(child);
  51174. }
  51175. }
  51176. return this;
  51177. };
  51178. /**
  51179. * Returns the associated light object.
  51180. */
  51181. ShadowGenerator.prototype.getLight = function () {
  51182. return this._light;
  51183. };
  51184. ShadowGenerator.prototype._initializeGenerator = function () {
  51185. this._light._markMeshesAsLightDirty();
  51186. this._initializeShadowMap();
  51187. };
  51188. ShadowGenerator.prototype._initializeShadowMap = function () {
  51189. var _this = this;
  51190. // Render target
  51191. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51192. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51193. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51194. this._shadowMap.anisotropicFilteringLevel = 1;
  51195. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51196. this._shadowMap.renderParticles = false;
  51197. this._shadowMap.ignoreCameraViewport = true;
  51198. // Record Face Index before render.
  51199. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51200. _this._currentFaceIndex = faceIndex;
  51201. });
  51202. // Custom render function.
  51203. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51204. // Blur if required afer render.
  51205. this._shadowMap.onAfterUnbindObservable.add(function () {
  51206. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51207. return;
  51208. }
  51209. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51210. _this._initializeBlurRTTAndPostProcesses();
  51211. }
  51212. var shadowMap = _this.getShadowMapForRendering();
  51213. if (shadowMap) {
  51214. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51215. }
  51216. });
  51217. // Clear according to the chosen filter.
  51218. this._shadowMap.onClearObservable.add(function (engine) {
  51219. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51220. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51221. }
  51222. else {
  51223. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51224. }
  51225. });
  51226. };
  51227. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51228. var _this = this;
  51229. var engine = this._scene.getEngine();
  51230. var targetSize = this._mapSize / this.blurScale;
  51231. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51232. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51233. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51234. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51235. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51236. }
  51237. if (this.useKernelBlur) {
  51238. 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);
  51239. this._kernelBlurXPostprocess.width = targetSize;
  51240. this._kernelBlurXPostprocess.height = targetSize;
  51241. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51242. effect.setTexture("textureSampler", _this._shadowMap);
  51243. });
  51244. 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);
  51245. this._kernelBlurXPostprocess.autoClear = false;
  51246. this._kernelBlurYPostprocess.autoClear = false;
  51247. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51248. this._kernelBlurXPostprocess.packedFloat = true;
  51249. this._kernelBlurYPostprocess.packedFloat = true;
  51250. }
  51251. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51252. }
  51253. else {
  51254. 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);
  51255. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51256. effect.setFloat2("screenSize", targetSize, targetSize);
  51257. effect.setTexture("textureSampler", _this._shadowMap);
  51258. });
  51259. this._boxBlurPostprocess.autoClear = false;
  51260. this._blurPostProcesses = [this._boxBlurPostprocess];
  51261. }
  51262. };
  51263. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51264. var index;
  51265. var engine = this._scene.getEngine();
  51266. if (depthOnlySubMeshes.length) {
  51267. engine.setColorWrite(false);
  51268. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51269. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51270. }
  51271. engine.setColorWrite(true);
  51272. }
  51273. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51274. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51275. }
  51276. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51277. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51278. }
  51279. if (this._transparencyShadow) {
  51280. for (index = 0; index < transparentSubMeshes.length; index++) {
  51281. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51282. }
  51283. }
  51284. };
  51285. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51286. var _this = this;
  51287. var mesh = subMesh.getRenderingMesh();
  51288. var scene = this._scene;
  51289. var engine = scene.getEngine();
  51290. var material = subMesh.getMaterial();
  51291. if (!material) {
  51292. return;
  51293. }
  51294. // Culling
  51295. engine.setState(material.backFaceCulling);
  51296. // Managing instances
  51297. var batch = mesh._getInstancesRenderList(subMesh._id);
  51298. if (batch.mustReturn) {
  51299. return;
  51300. }
  51301. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51302. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51303. engine.enableEffect(this._effect);
  51304. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51305. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51306. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51307. this._effect.setVector3("lightPosition", this.getLight().position);
  51308. if (scene.activeCamera) {
  51309. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51310. }
  51311. // Alpha test
  51312. if (material && material.needAlphaTesting()) {
  51313. var alphaTexture = material.getAlphaTestTexture();
  51314. if (alphaTexture) {
  51315. this._effect.setTexture("diffuseSampler", alphaTexture);
  51316. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51317. }
  51318. }
  51319. // Bones
  51320. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51321. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51322. }
  51323. if (this.forceBackFacesOnly) {
  51324. engine.setState(true, 0, false, true);
  51325. }
  51326. // Draw
  51327. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51328. if (this.forceBackFacesOnly) {
  51329. engine.setState(true, 0, false, false);
  51330. }
  51331. }
  51332. else {
  51333. // Need to reset refresh rate of the shadowMap
  51334. if (this._shadowMap) {
  51335. this._shadowMap.resetRefreshCounter();
  51336. }
  51337. }
  51338. };
  51339. ShadowGenerator.prototype._applyFilterValues = function () {
  51340. if (!this._shadowMap) {
  51341. return;
  51342. }
  51343. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51344. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51345. }
  51346. else {
  51347. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51348. }
  51349. };
  51350. /**
  51351. * Force shader compilation including textures ready check
  51352. */
  51353. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51354. var _this = this;
  51355. var shadowMap = this.getShadowMap();
  51356. if (!shadowMap) {
  51357. return;
  51358. }
  51359. var subMeshes = new Array();
  51360. var currentIndex = 0;
  51361. var renderList = shadowMap.renderList;
  51362. if (!renderList) {
  51363. return;
  51364. }
  51365. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51366. var mesh = renderList_1[_i];
  51367. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51368. }
  51369. var checkReady = function () {
  51370. if (!_this._scene || !_this._scene.getEngine()) {
  51371. return;
  51372. }
  51373. while (_this.isReady(subMeshes[currentIndex], options ? options.useInstances : false)) {
  51374. currentIndex++;
  51375. if (currentIndex >= subMeshes.length) {
  51376. if (onCompiled) {
  51377. onCompiled(_this);
  51378. }
  51379. return;
  51380. }
  51381. }
  51382. setTimeout(checkReady, 16);
  51383. };
  51384. if (subMeshes.length > 0) {
  51385. checkReady();
  51386. }
  51387. };
  51388. /**
  51389. * Boolean : true when the ShadowGenerator is finally computed.
  51390. */
  51391. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51392. var defines = [];
  51393. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51394. defines.push("#define FLOAT");
  51395. }
  51396. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51397. defines.push("#define ESM");
  51398. }
  51399. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51400. var mesh = subMesh.getMesh();
  51401. var material = subMesh.getMaterial();
  51402. // Alpha test
  51403. if (material && material.needAlphaTesting()) {
  51404. var alphaTexture = material.getAlphaTestTexture();
  51405. if (alphaTexture) {
  51406. defines.push("#define ALPHATEST");
  51407. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51408. attribs.push(BABYLON.VertexBuffer.UVKind);
  51409. defines.push("#define UV1");
  51410. }
  51411. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51412. if (alphaTexture.coordinatesIndex === 1) {
  51413. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51414. defines.push("#define UV2");
  51415. }
  51416. }
  51417. }
  51418. }
  51419. // Bones
  51420. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51421. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51422. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51423. if (mesh.numBoneInfluencers > 4) {
  51424. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51425. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51426. }
  51427. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51428. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51429. }
  51430. else {
  51431. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51432. }
  51433. // Instances
  51434. if (useInstances) {
  51435. defines.push("#define INSTANCES");
  51436. attribs.push("world0");
  51437. attribs.push("world1");
  51438. attribs.push("world2");
  51439. attribs.push("world3");
  51440. }
  51441. // Get correct effect
  51442. var join = defines.join("\n");
  51443. if (this._cachedDefines !== join) {
  51444. this._cachedDefines = join;
  51445. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51446. }
  51447. return this._effect.isReady();
  51448. };
  51449. /**
  51450. * This creates the defines related to the standard BJS materials.
  51451. */
  51452. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51453. var scene = this._scene;
  51454. var light = this._light;
  51455. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51456. return;
  51457. }
  51458. defines["SHADOW" + lightIndex] = true;
  51459. if (this.usePoissonSampling) {
  51460. defines["SHADOWPCF" + lightIndex] = true;
  51461. }
  51462. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51463. defines["SHADOWESM" + lightIndex] = true;
  51464. }
  51465. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51466. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51467. }
  51468. if (light.needCube()) {
  51469. defines["SHADOWCUBE" + lightIndex] = true;
  51470. }
  51471. };
  51472. /**
  51473. * This binds shadow lights related to the standard BJS materials.
  51474. * It implies the unifroms available on the materials are the standard BJS ones.
  51475. */
  51476. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51477. var light = this._light;
  51478. var scene = this._scene;
  51479. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51480. return;
  51481. }
  51482. var camera = scene.activeCamera;
  51483. if (!camera) {
  51484. return;
  51485. }
  51486. var shadowMap = this.getShadowMap();
  51487. if (!shadowMap) {
  51488. return;
  51489. }
  51490. if (!light.needCube()) {
  51491. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51492. }
  51493. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51494. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51495. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51496. };
  51497. // Methods
  51498. /**
  51499. * Returns a Matrix object : the updated transformation matrix.
  51500. */
  51501. ShadowGenerator.prototype.getTransformMatrix = function () {
  51502. var scene = this._scene;
  51503. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51504. return this._transformMatrix;
  51505. }
  51506. this._currentRenderID = scene.getRenderId();
  51507. this._currentFaceIndexCache = this._currentFaceIndex;
  51508. var lightPosition = this._light.position;
  51509. if (this._light.computeTransformedInformation()) {
  51510. lightPosition = this._light.transformedPosition;
  51511. }
  51512. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51513. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51514. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51515. }
  51516. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51517. this._cachedPosition = lightPosition.clone();
  51518. this._cachedDirection = this._lightDirection.clone();
  51519. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51520. var shadowMap = this.getShadowMap();
  51521. if (shadowMap) {
  51522. var renderList = shadowMap.renderList;
  51523. if (renderList) {
  51524. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51525. }
  51526. }
  51527. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51528. }
  51529. return this._transformMatrix;
  51530. };
  51531. ShadowGenerator.prototype.recreateShadowMap = function () {
  51532. var shadowMap = this._shadowMap;
  51533. if (!shadowMap) {
  51534. return;
  51535. }
  51536. // Track render list.
  51537. var renderList = shadowMap.renderList;
  51538. // Clean up existing data.
  51539. this._disposeRTTandPostProcesses();
  51540. // Reinitializes.
  51541. this._initializeGenerator();
  51542. // Reaffect the filter to ensure a correct fallback if necessary.
  51543. this.filter = this.filter;
  51544. // Reaffect the filter.
  51545. this._applyFilterValues();
  51546. // Reaffect Render List.
  51547. this._shadowMap.renderList = renderList;
  51548. };
  51549. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51550. if (this._shadowMap2) {
  51551. this._shadowMap2.dispose();
  51552. this._shadowMap2 = null;
  51553. }
  51554. if (this._downSamplePostprocess) {
  51555. this._downSamplePostprocess.dispose();
  51556. this._downSamplePostprocess = null;
  51557. }
  51558. if (this._boxBlurPostprocess) {
  51559. this._boxBlurPostprocess.dispose();
  51560. this._boxBlurPostprocess = null;
  51561. }
  51562. if (this._kernelBlurXPostprocess) {
  51563. this._kernelBlurXPostprocess.dispose();
  51564. this._kernelBlurXPostprocess = null;
  51565. }
  51566. if (this._kernelBlurYPostprocess) {
  51567. this._kernelBlurYPostprocess.dispose();
  51568. this._kernelBlurYPostprocess = null;
  51569. }
  51570. this._blurPostProcesses = [];
  51571. };
  51572. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51573. if (this._shadowMap) {
  51574. this._shadowMap.dispose();
  51575. this._shadowMap = null;
  51576. }
  51577. this._disposeBlurPostProcesses();
  51578. };
  51579. /**
  51580. * Disposes the ShadowGenerator.
  51581. * Returns nothing.
  51582. */
  51583. ShadowGenerator.prototype.dispose = function () {
  51584. this._disposeRTTandPostProcesses();
  51585. if (this._light) {
  51586. this._light._shadowGenerator = null;
  51587. this._light._markMeshesAsLightDirty();
  51588. }
  51589. };
  51590. /**
  51591. * Serializes the ShadowGenerator and returns a serializationObject.
  51592. */
  51593. ShadowGenerator.prototype.serialize = function () {
  51594. var serializationObject = {};
  51595. var shadowMap = this.getShadowMap();
  51596. if (!shadowMap) {
  51597. return serializationObject;
  51598. }
  51599. serializationObject.lightId = this._light.id;
  51600. serializationObject.mapSize = shadowMap.getRenderSize();
  51601. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51602. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51603. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51604. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51605. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51606. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51607. serializationObject.depthScale = this.depthScale;
  51608. serializationObject.darkness = this.getDarkness();
  51609. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51610. serializationObject.blurKernel = this.blurKernel;
  51611. serializationObject.blurScale = this.blurScale;
  51612. serializationObject.useKernelBlur = this.useKernelBlur;
  51613. serializationObject.transparencyShadow = this._transparencyShadow;
  51614. serializationObject.renderList = [];
  51615. if (shadowMap.renderList) {
  51616. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51617. var mesh = shadowMap.renderList[meshIndex];
  51618. serializationObject.renderList.push(mesh.id);
  51619. }
  51620. }
  51621. return serializationObject;
  51622. };
  51623. /**
  51624. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51625. */
  51626. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51627. //casting to point light, as light is missing the position attr and typescript complains.
  51628. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51629. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51630. var shadowMap = shadowGenerator.getShadowMap();
  51631. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51632. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51633. meshes.forEach(function (mesh) {
  51634. if (!shadowMap) {
  51635. return;
  51636. }
  51637. if (!shadowMap.renderList) {
  51638. shadowMap.renderList = [];
  51639. }
  51640. shadowMap.renderList.push(mesh);
  51641. });
  51642. }
  51643. if (parsedShadowGenerator.usePoissonSampling) {
  51644. shadowGenerator.usePoissonSampling = true;
  51645. }
  51646. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51647. shadowGenerator.useExponentialShadowMap = true;
  51648. }
  51649. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51650. shadowGenerator.useBlurExponentialShadowMap = true;
  51651. }
  51652. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51653. shadowGenerator.useCloseExponentialShadowMap = true;
  51654. }
  51655. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51656. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51657. }
  51658. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51659. shadowGenerator.useExponentialShadowMap = true;
  51660. }
  51661. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51662. shadowGenerator.useBlurExponentialShadowMap = true;
  51663. }
  51664. if (parsedShadowGenerator.depthScale) {
  51665. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51666. }
  51667. if (parsedShadowGenerator.blurScale) {
  51668. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51669. }
  51670. if (parsedShadowGenerator.blurBoxOffset) {
  51671. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51672. }
  51673. if (parsedShadowGenerator.useKernelBlur) {
  51674. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51675. }
  51676. if (parsedShadowGenerator.blurKernel) {
  51677. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51678. }
  51679. if (parsedShadowGenerator.bias !== undefined) {
  51680. shadowGenerator.bias = parsedShadowGenerator.bias;
  51681. }
  51682. if (parsedShadowGenerator.darkness) {
  51683. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51684. }
  51685. if (parsedShadowGenerator.transparencyShadow) {
  51686. shadowGenerator.setTransparencyShadow(true);
  51687. }
  51688. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51689. return shadowGenerator;
  51690. };
  51691. ShadowGenerator._FILTER_NONE = 0;
  51692. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51693. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51694. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51695. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51696. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51697. return ShadowGenerator;
  51698. }());
  51699. BABYLON.ShadowGenerator = ShadowGenerator;
  51700. })(BABYLON || (BABYLON = {}));
  51701. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51702. var BABYLON;
  51703. (function (BABYLON) {
  51704. var DefaultLoadingScreen = /** @class */ (function () {
  51705. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51706. if (_loadingText === void 0) { _loadingText = ""; }
  51707. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51708. var _this = this;
  51709. this._renderingCanvas = _renderingCanvas;
  51710. this._loadingText = _loadingText;
  51711. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51712. // Resize
  51713. this._resizeLoadingUI = function () {
  51714. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51715. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51716. if (!_this._loadingDiv) {
  51717. return;
  51718. }
  51719. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51720. _this._loadingDiv.style.left = canvasRect.left + "px";
  51721. _this._loadingDiv.style.top = canvasRect.top + "px";
  51722. _this._loadingDiv.style.width = canvasRect.width + "px";
  51723. _this._loadingDiv.style.height = canvasRect.height + "px";
  51724. };
  51725. }
  51726. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51727. if (this._loadingDiv) {
  51728. // Do not add a loading screen if there is already one
  51729. return;
  51730. }
  51731. this._loadingDiv = document.createElement("div");
  51732. this._loadingDiv.id = "babylonjsLoadingDiv";
  51733. this._loadingDiv.style.opacity = "0";
  51734. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51735. this._loadingDiv.style.pointerEvents = "none";
  51736. // Loading text
  51737. this._loadingTextDiv = document.createElement("div");
  51738. this._loadingTextDiv.style.position = "absolute";
  51739. this._loadingTextDiv.style.left = "0";
  51740. this._loadingTextDiv.style.top = "50%";
  51741. this._loadingTextDiv.style.marginTop = "80px";
  51742. this._loadingTextDiv.style.width = "100%";
  51743. this._loadingTextDiv.style.height = "20px";
  51744. this._loadingTextDiv.style.fontFamily = "Arial";
  51745. this._loadingTextDiv.style.fontSize = "14px";
  51746. this._loadingTextDiv.style.color = "white";
  51747. this._loadingTextDiv.style.textAlign = "center";
  51748. this._loadingTextDiv.innerHTML = "Loading";
  51749. this._loadingDiv.appendChild(this._loadingTextDiv);
  51750. //set the predefined text
  51751. this._loadingTextDiv.innerHTML = this._loadingText;
  51752. // Generating keyframes
  51753. var style = document.createElement('style');
  51754. style.type = 'text/css';
  51755. 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 }";
  51756. style.innerHTML = keyFrames;
  51757. document.getElementsByTagName('head')[0].appendChild(style);
  51758. // Loading img
  51759. var imgBack = new Image();
  51760. 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";
  51761. imgBack.style.position = "absolute";
  51762. imgBack.style.left = "50%";
  51763. imgBack.style.top = "50%";
  51764. imgBack.style.marginLeft = "-60px";
  51765. imgBack.style.marginTop = "-60px";
  51766. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51767. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51768. imgBack.style.transformOrigin = "50% 50%";
  51769. imgBack.style.webkitTransformOrigin = "50% 50%";
  51770. this._loadingDiv.appendChild(imgBack);
  51771. this._resizeLoadingUI();
  51772. window.addEventListener("resize", this._resizeLoadingUI);
  51773. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51774. document.body.appendChild(this._loadingDiv);
  51775. this._loadingDiv.style.opacity = "1";
  51776. };
  51777. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51778. var _this = this;
  51779. if (!this._loadingDiv) {
  51780. return;
  51781. }
  51782. var onTransitionEnd = function () {
  51783. if (!_this._loadingDiv) {
  51784. return;
  51785. }
  51786. document.body.removeChild(_this._loadingDiv);
  51787. window.removeEventListener("resize", _this._resizeLoadingUI);
  51788. _this._loadingDiv = null;
  51789. };
  51790. this._loadingDiv.style.opacity = "0";
  51791. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51792. };
  51793. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51794. set: function (text) {
  51795. this._loadingText = text;
  51796. if (this._loadingTextDiv) {
  51797. this._loadingTextDiv.innerHTML = this._loadingText;
  51798. }
  51799. },
  51800. enumerable: true,
  51801. configurable: true
  51802. });
  51803. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51804. get: function () {
  51805. return this._loadingDivBackgroundColor;
  51806. },
  51807. set: function (color) {
  51808. this._loadingDivBackgroundColor = color;
  51809. if (!this._loadingDiv) {
  51810. return;
  51811. }
  51812. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51813. },
  51814. enumerable: true,
  51815. configurable: true
  51816. });
  51817. return DefaultLoadingScreen;
  51818. }());
  51819. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51820. })(BABYLON || (BABYLON = {}));
  51821. //# sourceMappingURL=babylon.loadingScreen.js.map
  51822. var BABYLON;
  51823. (function (BABYLON) {
  51824. var SceneLoader = /** @class */ (function () {
  51825. function SceneLoader() {
  51826. }
  51827. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51828. get: function () {
  51829. return 0;
  51830. },
  51831. enumerable: true,
  51832. configurable: true
  51833. });
  51834. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51835. get: function () {
  51836. return 1;
  51837. },
  51838. enumerable: true,
  51839. configurable: true
  51840. });
  51841. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51842. get: function () {
  51843. return 2;
  51844. },
  51845. enumerable: true,
  51846. configurable: true
  51847. });
  51848. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51849. get: function () {
  51850. return 3;
  51851. },
  51852. enumerable: true,
  51853. configurable: true
  51854. });
  51855. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51856. get: function () {
  51857. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51858. },
  51859. set: function (value) {
  51860. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51861. },
  51862. enumerable: true,
  51863. configurable: true
  51864. });
  51865. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51866. get: function () {
  51867. return SceneLoader._ShowLoadingScreen;
  51868. },
  51869. set: function (value) {
  51870. SceneLoader._ShowLoadingScreen = value;
  51871. },
  51872. enumerable: true,
  51873. configurable: true
  51874. });
  51875. Object.defineProperty(SceneLoader, "loggingLevel", {
  51876. get: function () {
  51877. return SceneLoader._loggingLevel;
  51878. },
  51879. set: function (value) {
  51880. SceneLoader._loggingLevel = value;
  51881. },
  51882. enumerable: true,
  51883. configurable: true
  51884. });
  51885. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51886. get: function () {
  51887. return SceneLoader._CleanBoneMatrixWeights;
  51888. },
  51889. set: function (value) {
  51890. SceneLoader._CleanBoneMatrixWeights = value;
  51891. },
  51892. enumerable: true,
  51893. configurable: true
  51894. });
  51895. SceneLoader._getDefaultPlugin = function () {
  51896. return SceneLoader._registeredPlugins[".babylon"];
  51897. };
  51898. SceneLoader._getPluginForExtension = function (extension) {
  51899. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51900. if (registeredPlugin) {
  51901. return registeredPlugin;
  51902. }
  51903. return SceneLoader._getDefaultPlugin();
  51904. };
  51905. SceneLoader._getPluginForDirectLoad = function (data) {
  51906. for (var extension in SceneLoader._registeredPlugins) {
  51907. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51908. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51909. return SceneLoader._registeredPlugins[extension];
  51910. }
  51911. }
  51912. return SceneLoader._getDefaultPlugin();
  51913. };
  51914. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51915. if (sceneFilename.name) {
  51916. sceneFilename = sceneFilename.name;
  51917. }
  51918. var dotPosition = sceneFilename.lastIndexOf(".");
  51919. var queryStringPosition = sceneFilename.indexOf("?");
  51920. if (queryStringPosition === -1) {
  51921. queryStringPosition = sceneFilename.length;
  51922. }
  51923. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51924. return SceneLoader._getPluginForExtension(extension);
  51925. };
  51926. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51927. SceneLoader._getDirectLoad = function (sceneFilename) {
  51928. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51929. return sceneFilename.substr(5);
  51930. }
  51931. return null;
  51932. };
  51933. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  51934. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51935. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  51936. var plugin = registeredPlugin.plugin;
  51937. var useArrayBuffer = registeredPlugin.isBinary;
  51938. var database;
  51939. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51940. var dataCallback = function (data) {
  51941. if (scene.isDisposed) {
  51942. onError("Scene has been disposed");
  51943. return;
  51944. }
  51945. scene.database = database;
  51946. try {
  51947. onSuccess(plugin, data);
  51948. }
  51949. catch (e) {
  51950. onError(null, e);
  51951. }
  51952. };
  51953. var manifestChecked = function (success) {
  51954. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51955. if (request) {
  51956. onError(request.status + " " + request.statusText);
  51957. }
  51958. });
  51959. };
  51960. if (directLoad) {
  51961. dataCallback(directLoad);
  51962. return;
  51963. }
  51964. if (rootUrl.indexOf("file:") === -1) {
  51965. if (scene.getEngine().enableOfflineSupport) {
  51966. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51967. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51968. }
  51969. else {
  51970. manifestChecked(true);
  51971. }
  51972. }
  51973. else {
  51974. var fileOrString = sceneFilename;
  51975. if (fileOrString.name) {
  51976. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51977. }
  51978. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51979. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51980. }
  51981. else {
  51982. onError("Unable to find file named " + sceneFilename);
  51983. return;
  51984. }
  51985. }
  51986. };
  51987. // Public functions
  51988. SceneLoader.GetPluginForExtension = function (extension) {
  51989. return SceneLoader._getPluginForExtension(extension).plugin;
  51990. };
  51991. SceneLoader.RegisterPlugin = function (plugin) {
  51992. if (typeof plugin.extensions === "string") {
  51993. var extension = plugin.extensions;
  51994. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51995. plugin: plugin,
  51996. isBinary: false
  51997. };
  51998. }
  51999. else {
  52000. var extensions = plugin.extensions;
  52001. Object.keys(extensions).forEach(function (extension) {
  52002. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52003. plugin: plugin,
  52004. isBinary: extensions[extension].isBinary
  52005. };
  52006. });
  52007. }
  52008. };
  52009. /**
  52010. * Import meshes into a scene
  52011. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52012. * @param rootUrl a string that defines the root url for scene and resources
  52013. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52014. * @param scene the instance of BABYLON.Scene to append to
  52015. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52016. * @param onProgress a callback with a progress event for each file being loaded
  52017. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52018. */
  52019. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52020. if (onSuccess === void 0) { onSuccess = null; }
  52021. if (onProgress === void 0) { onProgress = null; }
  52022. if (onError === void 0) { onError = null; }
  52023. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52024. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52025. return;
  52026. }
  52027. var loadingToken = {};
  52028. scene._addPendingData(loadingToken);
  52029. var errorHandler = function (message, exception) {
  52030. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52031. if (onError) {
  52032. onError(scene, errorMessage, exception);
  52033. }
  52034. else {
  52035. BABYLON.Tools.Error(errorMessage);
  52036. // should the exception be thrown?
  52037. }
  52038. scene._removePendingData(loadingToken);
  52039. };
  52040. var progressHandler = function (event) {
  52041. if (onProgress) {
  52042. onProgress(event);
  52043. }
  52044. };
  52045. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52046. if (plugin.importMesh) {
  52047. var syncedPlugin = plugin;
  52048. var meshes = new Array();
  52049. var particleSystems = new Array();
  52050. var skeletons = new Array();
  52051. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52052. return;
  52053. }
  52054. if (onSuccess) {
  52055. // wrap onSuccess with try-catch to know if something went wrong.
  52056. try {
  52057. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52058. onSuccess(meshes, particleSystems, skeletons);
  52059. scene._removePendingData(loadingToken);
  52060. }
  52061. catch (e) {
  52062. var message = 'Error in onSuccess callback.';
  52063. errorHandler(message, e);
  52064. }
  52065. }
  52066. }
  52067. else {
  52068. var asyncedPlugin = plugin;
  52069. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52070. if (onSuccess) {
  52071. try {
  52072. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52073. onSuccess(meshes, particleSystems, skeletons);
  52074. scene._removePendingData(loadingToken);
  52075. }
  52076. catch (e) {
  52077. var message = 'Error in onSuccess callback.';
  52078. errorHandler(message, e);
  52079. }
  52080. }
  52081. }, progressHandler, errorHandler);
  52082. }
  52083. }, progressHandler, errorHandler, pluginExtension);
  52084. };
  52085. /**
  52086. * Load a scene
  52087. * @param rootUrl a string that defines the root url for scene and resources
  52088. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52089. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52090. * @param onSuccess a callback with the scene when import succeeds
  52091. * @param onProgress a callback with a progress event for each file being loaded
  52092. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52093. */
  52094. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52095. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52096. };
  52097. /**
  52098. * Append a scene
  52099. * @param rootUrl a string that defines the root url for scene and resources
  52100. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52101. * @param scene is the instance of BABYLON.Scene to append to
  52102. * @param onSuccess a callback with the scene when import succeeds
  52103. * @param onProgress a callback with a progress event for each file being loaded
  52104. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52105. */
  52106. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52107. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52108. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52109. return;
  52110. }
  52111. if (SceneLoader.ShowLoadingScreen) {
  52112. scene.getEngine().displayLoadingUI();
  52113. }
  52114. var loadingToken = {};
  52115. scene._addPendingData(loadingToken);
  52116. var errorHandler = function (message, exception) {
  52117. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52118. if (onError) {
  52119. onError(scene, errorMessage, exception);
  52120. }
  52121. else {
  52122. BABYLON.Tools.Error(errorMessage);
  52123. // should the exception be thrown?
  52124. }
  52125. scene._removePendingData(loadingToken);
  52126. scene.getEngine().hideLoadingUI();
  52127. };
  52128. var progressHandler = function (event) {
  52129. if (onProgress) {
  52130. onProgress(event);
  52131. }
  52132. };
  52133. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52134. if (plugin.load) {
  52135. var syncedPlugin = plugin;
  52136. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52137. return;
  52138. }
  52139. if (onSuccess) {
  52140. try {
  52141. onSuccess(scene);
  52142. }
  52143. catch (e) {
  52144. errorHandler("Error in onSuccess callback", e);
  52145. }
  52146. }
  52147. scene.loadingPluginName = plugin.name;
  52148. scene._removePendingData(loadingToken);
  52149. }
  52150. else {
  52151. var asyncedPlugin = plugin;
  52152. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52153. if (onSuccess) {
  52154. onSuccess(scene);
  52155. }
  52156. scene.loadingPluginName = plugin.name;
  52157. scene._removePendingData(loadingToken);
  52158. }, progressHandler, errorHandler);
  52159. }
  52160. if (SceneLoader.ShowLoadingScreen) {
  52161. scene.executeWhenReady(function () {
  52162. scene.getEngine().hideLoadingUI();
  52163. });
  52164. }
  52165. }, progressHandler, errorHandler, pluginExtension);
  52166. };
  52167. // Flags
  52168. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52169. SceneLoader._ShowLoadingScreen = true;
  52170. SceneLoader._CleanBoneMatrixWeights = false;
  52171. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52172. // Members
  52173. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52174. SceneLoader._registeredPlugins = {};
  52175. return SceneLoader;
  52176. }());
  52177. BABYLON.SceneLoader = SceneLoader;
  52178. ;
  52179. })(BABYLON || (BABYLON = {}));
  52180. //# sourceMappingURL=babylon.sceneLoader.js.map
  52181. var BABYLON;
  52182. (function (BABYLON) {
  52183. var Internals;
  52184. (function (Internals) {
  52185. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52186. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52187. var parsedMaterial = parsedData.materials[index];
  52188. if (parsedMaterial.id === id) {
  52189. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52190. }
  52191. }
  52192. return null;
  52193. };
  52194. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52195. for (var i in names) {
  52196. if (mesh.name === names[i]) {
  52197. hierarchyIds.push(mesh.id);
  52198. return true;
  52199. }
  52200. }
  52201. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52202. hierarchyIds.push(mesh.id);
  52203. return true;
  52204. }
  52205. return false;
  52206. };
  52207. var logOperation = function (operation, producer) {
  52208. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52209. };
  52210. BABYLON.SceneLoader.RegisterPlugin({
  52211. name: "babylon.js",
  52212. extensions: ".babylon",
  52213. canDirectLoad: function (data) {
  52214. if (data.indexOf("babylon") !== -1) {
  52215. return true;
  52216. }
  52217. return false;
  52218. },
  52219. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52220. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52221. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52222. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52223. // and avoid problems with multiple concurrent .babylon loads.
  52224. var log = "importMesh has failed JSON parse";
  52225. try {
  52226. var parsedData = JSON.parse(data);
  52227. log = "";
  52228. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52229. if (!meshesNames) {
  52230. meshesNames = null;
  52231. }
  52232. else if (!Array.isArray(meshesNames)) {
  52233. meshesNames = [meshesNames];
  52234. }
  52235. var hierarchyIds = new Array();
  52236. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52237. var loadedSkeletonsIds = [];
  52238. var loadedMaterialsIds = [];
  52239. var index;
  52240. var cache;
  52241. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52242. var parsedMesh = parsedData.meshes[index];
  52243. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52244. if (meshesNames !== null) {
  52245. // Remove found mesh name from list.
  52246. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52247. }
  52248. //Geometry?
  52249. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52250. //does the file contain geometries?
  52251. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52252. //find the correct geometry and add it to the scene
  52253. var found = false;
  52254. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52255. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52256. return;
  52257. }
  52258. else {
  52259. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52260. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52261. switch (geometryType) {
  52262. case "boxes":
  52263. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52264. break;
  52265. case "spheres":
  52266. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52267. break;
  52268. case "cylinders":
  52269. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52270. break;
  52271. case "toruses":
  52272. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52273. break;
  52274. case "grounds":
  52275. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52276. break;
  52277. case "planes":
  52278. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52279. break;
  52280. case "torusKnots":
  52281. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52282. break;
  52283. case "vertexData":
  52284. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52285. break;
  52286. }
  52287. found = true;
  52288. }
  52289. });
  52290. }
  52291. });
  52292. if (found === false) {
  52293. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52294. }
  52295. }
  52296. }
  52297. // Material ?
  52298. if (parsedMesh.materialId) {
  52299. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52300. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52301. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52302. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52303. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52304. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52305. var subMatId = parsedMultiMaterial.materials[matIndex];
  52306. loadedMaterialsIds.push(subMatId);
  52307. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52308. log += "\n\tMaterial " + mat.toString(fullDetails);
  52309. }
  52310. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52311. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52312. materialFound = true;
  52313. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52314. break;
  52315. }
  52316. }
  52317. }
  52318. if (materialFound === false) {
  52319. loadedMaterialsIds.push(parsedMesh.materialId);
  52320. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52321. if (!mat) {
  52322. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52323. }
  52324. else {
  52325. log += "\n\tMaterial " + mat.toString(fullDetails);
  52326. }
  52327. }
  52328. }
  52329. // Skeleton ?
  52330. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52331. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52332. if (skeletonAlreadyLoaded === false) {
  52333. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52334. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52335. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52336. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52337. skeletons.push(skeleton);
  52338. loadedSkeletonsIds.push(parsedSkeleton.id);
  52339. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52340. }
  52341. }
  52342. }
  52343. }
  52344. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52345. meshes.push(mesh);
  52346. log += "\n\tMesh " + mesh.toString(fullDetails);
  52347. }
  52348. }
  52349. // Connecting parents
  52350. var currentMesh;
  52351. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52352. currentMesh = scene.meshes[index];
  52353. if (currentMesh._waitingParentId) {
  52354. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52355. currentMesh._waitingParentId = null;
  52356. }
  52357. }
  52358. // freeze and compute world matrix application
  52359. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52360. currentMesh = scene.meshes[index];
  52361. if (currentMesh._waitingFreezeWorldMatrix) {
  52362. currentMesh.freezeWorldMatrix();
  52363. currentMesh._waitingFreezeWorldMatrix = null;
  52364. }
  52365. else {
  52366. currentMesh.computeWorldMatrix(true);
  52367. }
  52368. }
  52369. }
  52370. // Particles
  52371. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52372. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52373. var parsedParticleSystem = parsedData.particleSystems[index];
  52374. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52375. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52376. }
  52377. }
  52378. }
  52379. return true;
  52380. }
  52381. catch (err) {
  52382. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52383. if (onError) {
  52384. onError(msg, err);
  52385. }
  52386. else {
  52387. BABYLON.Tools.Log(msg);
  52388. throw err;
  52389. }
  52390. }
  52391. finally {
  52392. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52393. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52394. }
  52395. }
  52396. return false;
  52397. },
  52398. load: function (scene, data, rootUrl, onError) {
  52399. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52400. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52401. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52402. // and avoid problems with multiple concurrent .babylon loads.
  52403. var log = "importScene has failed JSON parse";
  52404. try {
  52405. var parsedData = JSON.parse(data);
  52406. log = "";
  52407. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52408. // Scene
  52409. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52410. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52411. }
  52412. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52413. scene.autoClear = parsedData.autoClear;
  52414. }
  52415. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52416. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52417. }
  52418. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52419. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52420. }
  52421. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52422. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52423. }
  52424. // Fog
  52425. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52426. scene.fogMode = parsedData.fogMode;
  52427. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52428. scene.fogStart = parsedData.fogStart;
  52429. scene.fogEnd = parsedData.fogEnd;
  52430. scene.fogDensity = parsedData.fogDensity;
  52431. log += "\tFog mode for scene: ";
  52432. switch (scene.fogMode) {
  52433. // getters not compiling, so using hardcoded
  52434. case 1:
  52435. log += "exp\n";
  52436. break;
  52437. case 2:
  52438. log += "exp2\n";
  52439. break;
  52440. case 3:
  52441. log += "linear\n";
  52442. break;
  52443. }
  52444. }
  52445. //Physics
  52446. if (parsedData.physicsEnabled) {
  52447. var physicsPlugin;
  52448. if (parsedData.physicsEngine === "cannon") {
  52449. physicsPlugin = new BABYLON.CannonJSPlugin();
  52450. }
  52451. else if (parsedData.physicsEngine === "oimo") {
  52452. physicsPlugin = new BABYLON.OimoJSPlugin();
  52453. }
  52454. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52455. //else - default engine, which is currently oimo
  52456. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52457. scene.enablePhysics(physicsGravity, physicsPlugin);
  52458. }
  52459. // Metadata
  52460. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52461. scene.metadata = parsedData.metadata;
  52462. }
  52463. //collisions, if defined. otherwise, default is true
  52464. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52465. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52466. }
  52467. scene.workerCollisions = !!parsedData.workerCollisions;
  52468. var index;
  52469. var cache;
  52470. // Lights
  52471. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52472. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52473. var parsedLight = parsedData.lights[index];
  52474. var light = BABYLON.Light.Parse(parsedLight, scene);
  52475. if (light) {
  52476. log += (index === 0 ? "\n\tLights:" : "");
  52477. log += "\n\t\t" + light.toString(fullDetails);
  52478. }
  52479. }
  52480. }
  52481. // Animations
  52482. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52483. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52484. var parsedAnimation = parsedData.animations[index];
  52485. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52486. scene.animations.push(animation);
  52487. log += (index === 0 ? "\n\tAnimations:" : "");
  52488. log += "\n\t\t" + animation.toString(fullDetails);
  52489. }
  52490. }
  52491. if (parsedData.autoAnimate) {
  52492. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52493. }
  52494. // Materials
  52495. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52496. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52497. var parsedMaterial = parsedData.materials[index];
  52498. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52499. log += (index === 0 ? "\n\tMaterials:" : "");
  52500. log += "\n\t\t" + mat.toString(fullDetails);
  52501. }
  52502. }
  52503. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52504. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52505. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52506. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52507. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52508. log += "\n\t\t" + mmat.toString(fullDetails);
  52509. }
  52510. }
  52511. // Morph targets
  52512. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52513. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52514. var managerData = _a[_i];
  52515. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52516. }
  52517. }
  52518. // Skeletons
  52519. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52520. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52521. var parsedSkeleton = parsedData.skeletons[index];
  52522. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52523. log += (index === 0 ? "\n\tSkeletons:" : "");
  52524. log += "\n\t\t" + skeleton.toString(fullDetails);
  52525. }
  52526. }
  52527. // Geometries
  52528. var geometries = parsedData.geometries;
  52529. if (geometries !== undefined && geometries !== null) {
  52530. // Boxes
  52531. var boxes = geometries.boxes;
  52532. if (boxes !== undefined && boxes !== null) {
  52533. for (index = 0, cache = boxes.length; index < cache; index++) {
  52534. var parsedBox = boxes[index];
  52535. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52536. }
  52537. }
  52538. // Spheres
  52539. var spheres = geometries.spheres;
  52540. if (spheres !== undefined && spheres !== null) {
  52541. for (index = 0, cache = spheres.length; index < cache; index++) {
  52542. var parsedSphere = spheres[index];
  52543. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52544. }
  52545. }
  52546. // Cylinders
  52547. var cylinders = geometries.cylinders;
  52548. if (cylinders !== undefined && cylinders !== null) {
  52549. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52550. var parsedCylinder = cylinders[index];
  52551. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52552. }
  52553. }
  52554. // Toruses
  52555. var toruses = geometries.toruses;
  52556. if (toruses !== undefined && toruses !== null) {
  52557. for (index = 0, cache = toruses.length; index < cache; index++) {
  52558. var parsedTorus = toruses[index];
  52559. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52560. }
  52561. }
  52562. // Grounds
  52563. var grounds = geometries.grounds;
  52564. if (grounds !== undefined && grounds !== null) {
  52565. for (index = 0, cache = grounds.length; index < cache; index++) {
  52566. var parsedGround = grounds[index];
  52567. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52568. }
  52569. }
  52570. // Planes
  52571. var planes = geometries.planes;
  52572. if (planes !== undefined && planes !== null) {
  52573. for (index = 0, cache = planes.length; index < cache; index++) {
  52574. var parsedPlane = planes[index];
  52575. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52576. }
  52577. }
  52578. // TorusKnots
  52579. var torusKnots = geometries.torusKnots;
  52580. if (torusKnots !== undefined && torusKnots !== null) {
  52581. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52582. var parsedTorusKnot = torusKnots[index];
  52583. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52584. }
  52585. }
  52586. // VertexData
  52587. var vertexData = geometries.vertexData;
  52588. if (vertexData !== undefined && vertexData !== null) {
  52589. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52590. var parsedVertexData = vertexData[index];
  52591. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52592. }
  52593. }
  52594. }
  52595. // Meshes
  52596. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52597. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52598. var parsedMesh = parsedData.meshes[index];
  52599. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52600. log += (index === 0 ? "\n\tMeshes:" : "");
  52601. log += "\n\t\t" + mesh.toString(fullDetails);
  52602. }
  52603. }
  52604. // Cameras
  52605. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52606. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52607. var parsedCamera = parsedData.cameras[index];
  52608. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52609. log += (index === 0 ? "\n\tCameras:" : "");
  52610. log += "\n\t\t" + camera.toString(fullDetails);
  52611. }
  52612. }
  52613. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52614. scene.setActiveCameraByID(parsedData.activeCameraID);
  52615. }
  52616. // Browsing all the graph to connect the dots
  52617. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52618. var camera = scene.cameras[index];
  52619. if (camera._waitingParentId) {
  52620. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52621. camera._waitingParentId = null;
  52622. }
  52623. }
  52624. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52625. var light_1 = scene.lights[index];
  52626. if (light_1 && light_1._waitingParentId) {
  52627. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52628. light_1._waitingParentId = null;
  52629. }
  52630. }
  52631. // Sounds
  52632. var loadedSounds = [];
  52633. var loadedSound;
  52634. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52635. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52636. var parsedSound = parsedData.sounds[index];
  52637. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52638. if (!parsedSound.url)
  52639. parsedSound.url = parsedSound.name;
  52640. if (!loadedSounds[parsedSound.url]) {
  52641. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52642. loadedSounds[parsedSound.url] = loadedSound;
  52643. }
  52644. else {
  52645. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52646. }
  52647. }
  52648. else {
  52649. new BABYLON.Sound(parsedSound.name, null, scene);
  52650. }
  52651. }
  52652. }
  52653. loadedSounds = [];
  52654. // Connect parents & children and parse actions
  52655. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52656. var mesh = scene.meshes[index];
  52657. if (mesh._waitingParentId) {
  52658. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52659. mesh._waitingParentId = null;
  52660. }
  52661. if (mesh._waitingActions) {
  52662. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52663. mesh._waitingActions = null;
  52664. }
  52665. }
  52666. // freeze world matrix application
  52667. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52668. var currentMesh = scene.meshes[index];
  52669. if (currentMesh._waitingFreezeWorldMatrix) {
  52670. currentMesh.freezeWorldMatrix();
  52671. currentMesh._waitingFreezeWorldMatrix = null;
  52672. }
  52673. else {
  52674. currentMesh.computeWorldMatrix(true);
  52675. }
  52676. }
  52677. // Particles Systems
  52678. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52679. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52680. var parsedParticleSystem = parsedData.particleSystems[index];
  52681. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52682. }
  52683. }
  52684. // Environment texture
  52685. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52686. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52687. if (parsedData.createDefaultSkybox === true) {
  52688. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52689. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52690. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52691. }
  52692. }
  52693. // Lens flares
  52694. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52695. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52696. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52697. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52698. }
  52699. }
  52700. // Shadows
  52701. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52702. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52703. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52704. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52705. }
  52706. }
  52707. // Lights exclusions / inclusions
  52708. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52709. var light_2 = scene.lights[index];
  52710. // Excluded check
  52711. if (light_2._excludedMeshesIds.length > 0) {
  52712. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52713. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52714. if (excludedMesh) {
  52715. light_2.excludedMeshes.push(excludedMesh);
  52716. }
  52717. }
  52718. light_2._excludedMeshesIds = [];
  52719. }
  52720. // Included check
  52721. if (light_2._includedOnlyMeshesIds.length > 0) {
  52722. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52723. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52724. if (includedOnlyMesh) {
  52725. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52726. }
  52727. }
  52728. light_2._includedOnlyMeshesIds = [];
  52729. }
  52730. }
  52731. // Actions (scene)
  52732. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52733. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52734. }
  52735. // Finish
  52736. return true;
  52737. }
  52738. catch (err) {
  52739. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52740. if (onError) {
  52741. onError(msg, err);
  52742. }
  52743. else {
  52744. BABYLON.Tools.Log(msg);
  52745. throw err;
  52746. }
  52747. }
  52748. finally {
  52749. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52750. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52751. }
  52752. }
  52753. return false;
  52754. }
  52755. });
  52756. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52757. })(BABYLON || (BABYLON = {}));
  52758. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52759. var BABYLON;
  52760. (function (BABYLON) {
  52761. var FilesInput = /** @class */ (function () {
  52762. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52763. this.onProcessFileCallback = function () { return true; };
  52764. this._engine = engine;
  52765. this._currentScene = scene;
  52766. this._sceneLoadedCallback = sceneLoadedCallback;
  52767. this._progressCallback = progressCallback;
  52768. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52769. this._textureLoadingCallback = textureLoadingCallback;
  52770. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52771. this._onReloadCallback = onReloadCallback;
  52772. this._errorCallback = errorCallback;
  52773. }
  52774. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52775. var _this = this;
  52776. if (elementToMonitor) {
  52777. this._elementToMonitor = elementToMonitor;
  52778. this._dragEnterHandler = function (e) { _this.drag(e); };
  52779. this._dragOverHandler = function (e) { _this.drag(e); };
  52780. this._dropHandler = function (e) { _this.drop(e); };
  52781. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52782. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52783. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52784. }
  52785. };
  52786. FilesInput.prototype.dispose = function () {
  52787. if (!this._elementToMonitor) {
  52788. return;
  52789. }
  52790. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52791. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52792. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52793. };
  52794. FilesInput.prototype.renderFunction = function () {
  52795. if (this._additionalRenderLoopLogicCallback) {
  52796. this._additionalRenderLoopLogicCallback();
  52797. }
  52798. if (this._currentScene) {
  52799. if (this._textureLoadingCallback) {
  52800. var remaining = this._currentScene.getWaitingItemsCount();
  52801. if (remaining > 0) {
  52802. this._textureLoadingCallback(remaining);
  52803. }
  52804. }
  52805. this._currentScene.render();
  52806. }
  52807. };
  52808. FilesInput.prototype.drag = function (e) {
  52809. e.stopPropagation();
  52810. e.preventDefault();
  52811. };
  52812. FilesInput.prototype.drop = function (eventDrop) {
  52813. eventDrop.stopPropagation();
  52814. eventDrop.preventDefault();
  52815. this.loadFiles(eventDrop);
  52816. };
  52817. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52818. var _this = this;
  52819. var reader = folder.createReader();
  52820. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52821. reader.readEntries(function (entries) {
  52822. remaining.count += entries.length;
  52823. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52824. var entry = entries_1[_i];
  52825. if (entry.isFile) {
  52826. entry.file(function (file) {
  52827. file.correctName = relativePath + file.name;
  52828. files.push(file);
  52829. if (--remaining.count === 0) {
  52830. callback();
  52831. }
  52832. });
  52833. }
  52834. else if (entry.isDirectory) {
  52835. _this._traverseFolder(entry, files, remaining, callback);
  52836. }
  52837. }
  52838. if (--remaining.count) {
  52839. callback();
  52840. }
  52841. });
  52842. };
  52843. FilesInput.prototype._processFiles = function (files) {
  52844. var skippedFiles = 0;
  52845. for (var i = 0; i < files.length; i++) {
  52846. var name = files[i].correctName.toLowerCase();
  52847. var extension = name.split('.').pop();
  52848. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52849. skippedFiles++;
  52850. continue;
  52851. }
  52852. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52853. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52854. this._sceneFileToLoad = files[i];
  52855. }
  52856. else {
  52857. FilesInput.FilesToLoad[name] = files[i];
  52858. }
  52859. }
  52860. if (this._onReloadCallback) {
  52861. this._onReloadCallback(this._sceneFileToLoad);
  52862. }
  52863. else if (skippedFiles < files.length) {
  52864. this.reload();
  52865. }
  52866. };
  52867. FilesInput.prototype.loadFiles = function (event) {
  52868. var _this = this;
  52869. if (this._startingProcessingFilesCallback)
  52870. this._startingProcessingFilesCallback();
  52871. // Handling data transfer via drag'n'drop
  52872. if (event && event.dataTransfer && event.dataTransfer.files) {
  52873. this._filesToLoad = event.dataTransfer.files;
  52874. }
  52875. // Handling files from input files
  52876. if (event && event.target && event.target.files) {
  52877. this._filesToLoad = event.target.files;
  52878. }
  52879. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52880. var files_1 = new Array();
  52881. var folders = [];
  52882. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52883. for (var i = 0; i < this._filesToLoad.length; i++) {
  52884. var fileToLoad = this._filesToLoad[i];
  52885. var name_1 = fileToLoad.name.toLowerCase();
  52886. var entry = void 0;
  52887. fileToLoad.correctName = name_1;
  52888. if (items) {
  52889. var item = items[i];
  52890. if (item.getAsEntry) {
  52891. entry = item.getAsEntry();
  52892. }
  52893. else if (item.webkitGetAsEntry) {
  52894. entry = item.webkitGetAsEntry();
  52895. }
  52896. }
  52897. if (!entry) {
  52898. files_1.push(fileToLoad);
  52899. }
  52900. else {
  52901. if (entry.isDirectory) {
  52902. folders.push(entry);
  52903. }
  52904. else {
  52905. files_1.push(fileToLoad);
  52906. }
  52907. }
  52908. }
  52909. if (folders.length === 0) {
  52910. this._processFiles(files_1);
  52911. }
  52912. else {
  52913. var remaining = { count: folders.length };
  52914. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52915. var folder = folders_1[_i];
  52916. this._traverseFolder(folder, files_1, remaining, function () {
  52917. _this._processFiles(files_1);
  52918. });
  52919. }
  52920. }
  52921. }
  52922. };
  52923. FilesInput.prototype.reload = function () {
  52924. var _this = this;
  52925. // If a ".babylon" file has been provided
  52926. if (this._sceneFileToLoad) {
  52927. if (this._currentScene) {
  52928. if (BABYLON.Tools.errorsCount > 0) {
  52929. BABYLON.Tools.ClearLogCache();
  52930. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52931. }
  52932. this._engine.stopRenderLoop();
  52933. this._currentScene.dispose();
  52934. }
  52935. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52936. _this._currentScene = newScene;
  52937. if (_this._sceneLoadedCallback) {
  52938. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52939. }
  52940. // Wait for textures and shaders to be ready
  52941. _this._currentScene.executeWhenReady(function () {
  52942. _this._engine.runRenderLoop(function () {
  52943. _this.renderFunction();
  52944. });
  52945. });
  52946. }, function (progress) {
  52947. if (_this._progressCallback) {
  52948. _this._progressCallback(progress);
  52949. }
  52950. }, function (scene, message) {
  52951. _this._currentScene = scene;
  52952. if (_this._errorCallback) {
  52953. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52954. }
  52955. });
  52956. }
  52957. else {
  52958. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52959. }
  52960. };
  52961. FilesInput.FilesToLoad = {};
  52962. return FilesInput;
  52963. }());
  52964. BABYLON.FilesInput = FilesInput;
  52965. })(BABYLON || (BABYLON = {}));
  52966. //# sourceMappingURL=babylon.filesInput.js.map
  52967. var BABYLON;
  52968. (function (BABYLON) {
  52969. /**
  52970. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52971. * The underlying implementation relies on an associative array to ensure the best performances.
  52972. * The value can be anything including 'null' but except 'undefined'
  52973. */
  52974. var StringDictionary = /** @class */ (function () {
  52975. function StringDictionary() {
  52976. this._count = 0;
  52977. this._data = {};
  52978. }
  52979. /**
  52980. * This will clear this dictionary and copy the content from the 'source' one.
  52981. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52982. * @param source the dictionary to take the content from and copy to this dictionary
  52983. */
  52984. StringDictionary.prototype.copyFrom = function (source) {
  52985. var _this = this;
  52986. this.clear();
  52987. source.forEach(function (t, v) { return _this.add(t, v); });
  52988. };
  52989. /**
  52990. * Get a value based from its key
  52991. * @param key the given key to get the matching value from
  52992. * @return the value if found, otherwise undefined is returned
  52993. */
  52994. StringDictionary.prototype.get = function (key) {
  52995. var val = this._data[key];
  52996. if (val !== undefined) {
  52997. return val;
  52998. }
  52999. return undefined;
  53000. };
  53001. /**
  53002. * Get a value from its key or add it if it doesn't exist.
  53003. * This method will ensure you that a given key/data will be present in the dictionary.
  53004. * @param key the given key to get the matching value from
  53005. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53006. * The factory will only be invoked if there's no data for the given key.
  53007. * @return the value corresponding to the key.
  53008. */
  53009. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53010. var val = this.get(key);
  53011. if (val !== undefined) {
  53012. return val;
  53013. }
  53014. val = factory(key);
  53015. if (val) {
  53016. this.add(key, val);
  53017. }
  53018. return val;
  53019. };
  53020. /**
  53021. * Get a value from its key if present in the dictionary otherwise add it
  53022. * @param key the key to get the value from
  53023. * @param val if there's no such key/value pair in the dictionary add it with this value
  53024. * @return the value corresponding to the key
  53025. */
  53026. StringDictionary.prototype.getOrAdd = function (key, val) {
  53027. var curVal = this.get(key);
  53028. if (curVal !== undefined) {
  53029. return curVal;
  53030. }
  53031. this.add(key, val);
  53032. return val;
  53033. };
  53034. /**
  53035. * Check if there's a given key in the dictionary
  53036. * @param key the key to check for
  53037. * @return true if the key is present, false otherwise
  53038. */
  53039. StringDictionary.prototype.contains = function (key) {
  53040. return this._data[key] !== undefined;
  53041. };
  53042. /**
  53043. * Add a new key and its corresponding value
  53044. * @param key the key to add
  53045. * @param value the value corresponding to the key
  53046. * @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
  53047. */
  53048. StringDictionary.prototype.add = function (key, value) {
  53049. if (this._data[key] !== undefined) {
  53050. return false;
  53051. }
  53052. this._data[key] = value;
  53053. ++this._count;
  53054. return true;
  53055. };
  53056. StringDictionary.prototype.set = function (key, value) {
  53057. if (this._data[key] === undefined) {
  53058. return false;
  53059. }
  53060. this._data[key] = value;
  53061. return true;
  53062. };
  53063. /**
  53064. * Get the element of the given key and remove it from the dictionary
  53065. * @param key
  53066. */
  53067. StringDictionary.prototype.getAndRemove = function (key) {
  53068. var val = this.get(key);
  53069. if (val !== undefined) {
  53070. delete this._data[key];
  53071. --this._count;
  53072. return val;
  53073. }
  53074. return null;
  53075. };
  53076. /**
  53077. * Remove a key/value from the dictionary.
  53078. * @param key the key to remove
  53079. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53080. */
  53081. StringDictionary.prototype.remove = function (key) {
  53082. if (this.contains(key)) {
  53083. delete this._data[key];
  53084. --this._count;
  53085. return true;
  53086. }
  53087. return false;
  53088. };
  53089. /**
  53090. * Clear the whole content of the dictionary
  53091. */
  53092. StringDictionary.prototype.clear = function () {
  53093. this._data = {};
  53094. this._count = 0;
  53095. };
  53096. Object.defineProperty(StringDictionary.prototype, "count", {
  53097. get: function () {
  53098. return this._count;
  53099. },
  53100. enumerable: true,
  53101. configurable: true
  53102. });
  53103. /**
  53104. * Execute a callback on each key/val of the dictionary.
  53105. * Note that you can remove any element in this dictionary in the callback implementation
  53106. * @param callback the callback to execute on a given key/value pair
  53107. */
  53108. StringDictionary.prototype.forEach = function (callback) {
  53109. for (var cur in this._data) {
  53110. var val = this._data[cur];
  53111. callback(cur, val);
  53112. }
  53113. };
  53114. /**
  53115. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53116. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53117. * Note that you can remove any element in this dictionary in the callback implementation
  53118. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53119. */
  53120. StringDictionary.prototype.first = function (callback) {
  53121. for (var cur in this._data) {
  53122. var val = this._data[cur];
  53123. var res = callback(cur, val);
  53124. if (res) {
  53125. return res;
  53126. }
  53127. }
  53128. return null;
  53129. };
  53130. return StringDictionary;
  53131. }());
  53132. BABYLON.StringDictionary = StringDictionary;
  53133. })(BABYLON || (BABYLON = {}));
  53134. //# sourceMappingURL=babylon.stringDictionary.js.map
  53135. var BABYLON;
  53136. (function (BABYLON) {
  53137. var Tags = /** @class */ (function () {
  53138. function Tags() {
  53139. }
  53140. Tags.EnableFor = function (obj) {
  53141. obj._tags = obj._tags || {};
  53142. obj.hasTags = function () {
  53143. return Tags.HasTags(obj);
  53144. };
  53145. obj.addTags = function (tagsString) {
  53146. return Tags.AddTagsTo(obj, tagsString);
  53147. };
  53148. obj.removeTags = function (tagsString) {
  53149. return Tags.RemoveTagsFrom(obj, tagsString);
  53150. };
  53151. obj.matchesTagsQuery = function (tagsQuery) {
  53152. return Tags.MatchesQuery(obj, tagsQuery);
  53153. };
  53154. };
  53155. Tags.DisableFor = function (obj) {
  53156. delete obj._tags;
  53157. delete obj.hasTags;
  53158. delete obj.addTags;
  53159. delete obj.removeTags;
  53160. delete obj.matchesTagsQuery;
  53161. };
  53162. Tags.HasTags = function (obj) {
  53163. if (!obj._tags) {
  53164. return false;
  53165. }
  53166. return !BABYLON.Tools.IsEmpty(obj._tags);
  53167. };
  53168. Tags.GetTags = function (obj, asString) {
  53169. if (asString === void 0) { asString = true; }
  53170. if (!obj._tags) {
  53171. return null;
  53172. }
  53173. if (asString) {
  53174. var tagsArray = [];
  53175. for (var tag in obj._tags) {
  53176. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53177. tagsArray.push(tag);
  53178. }
  53179. }
  53180. return tagsArray.join(" ");
  53181. }
  53182. else {
  53183. return obj._tags;
  53184. }
  53185. };
  53186. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53187. // a tag cannot start with '||', '&&', and '!'
  53188. // it cannot contain whitespaces
  53189. Tags.AddTagsTo = function (obj, tagsString) {
  53190. if (!tagsString) {
  53191. return;
  53192. }
  53193. if (typeof tagsString !== "string") {
  53194. return;
  53195. }
  53196. var tags = tagsString.split(" ");
  53197. tags.forEach(function (tag, index, array) {
  53198. Tags._AddTagTo(obj, tag);
  53199. });
  53200. };
  53201. Tags._AddTagTo = function (obj, tag) {
  53202. tag = tag.trim();
  53203. if (tag === "" || tag === "true" || tag === "false") {
  53204. return;
  53205. }
  53206. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53207. return;
  53208. }
  53209. Tags.EnableFor(obj);
  53210. obj._tags[tag] = true;
  53211. };
  53212. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53213. if (!Tags.HasTags(obj)) {
  53214. return;
  53215. }
  53216. var tags = tagsString.split(" ");
  53217. for (var t in tags) {
  53218. Tags._RemoveTagFrom(obj, tags[t]);
  53219. }
  53220. };
  53221. Tags._RemoveTagFrom = function (obj, tag) {
  53222. delete obj._tags[tag];
  53223. };
  53224. Tags.MatchesQuery = function (obj, tagsQuery) {
  53225. if (tagsQuery === undefined) {
  53226. return true;
  53227. }
  53228. if (tagsQuery === "") {
  53229. return Tags.HasTags(obj);
  53230. }
  53231. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53232. };
  53233. return Tags;
  53234. }());
  53235. BABYLON.Tags = Tags;
  53236. })(BABYLON || (BABYLON = {}));
  53237. //# sourceMappingURL=babylon.tags.js.map
  53238. var BABYLON;
  53239. (function (BABYLON) {
  53240. var Internals;
  53241. (function (Internals) {
  53242. var AndOrNotEvaluator = /** @class */ (function () {
  53243. function AndOrNotEvaluator() {
  53244. }
  53245. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53246. if (!query.match(/\([^\(\)]*\)/g)) {
  53247. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53248. }
  53249. else {
  53250. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53251. // remove parenthesis
  53252. r = r.slice(1, r.length - 1);
  53253. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53254. });
  53255. }
  53256. if (query === "true") {
  53257. return true;
  53258. }
  53259. if (query === "false") {
  53260. return false;
  53261. }
  53262. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53263. };
  53264. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53265. evaluateCallback = evaluateCallback || (function (r) {
  53266. return r === "true" ? true : false;
  53267. });
  53268. var result;
  53269. var or = parenthesisContent.split("||");
  53270. for (var i in or) {
  53271. if (or.hasOwnProperty(i)) {
  53272. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53273. var and = ori.split("&&");
  53274. if (and.length > 1) {
  53275. for (var j = 0; j < and.length; ++j) {
  53276. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53277. if (andj !== "true" && andj !== "false") {
  53278. if (andj[0] === "!") {
  53279. result = !evaluateCallback(andj.substring(1));
  53280. }
  53281. else {
  53282. result = evaluateCallback(andj);
  53283. }
  53284. }
  53285. else {
  53286. result = andj === "true" ? true : false;
  53287. }
  53288. if (!result) {
  53289. ori = "false";
  53290. break;
  53291. }
  53292. }
  53293. }
  53294. if (result || ori === "true") {
  53295. result = true;
  53296. break;
  53297. }
  53298. // result equals false (or undefined)
  53299. if (ori !== "true" && ori !== "false") {
  53300. if (ori[0] === "!") {
  53301. result = !evaluateCallback(ori.substring(1));
  53302. }
  53303. else {
  53304. result = evaluateCallback(ori);
  53305. }
  53306. }
  53307. else {
  53308. result = ori === "true" ? true : false;
  53309. }
  53310. }
  53311. }
  53312. // the whole parenthesis scope is replaced by 'true' or 'false'
  53313. return result ? "true" : "false";
  53314. };
  53315. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53316. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53317. // remove whitespaces
  53318. r = r.replace(/[\s]/g, function () { return ""; });
  53319. return r.length % 2 ? "!" : "";
  53320. });
  53321. booleanString = booleanString.trim();
  53322. if (booleanString === "!true") {
  53323. booleanString = "false";
  53324. }
  53325. else if (booleanString === "!false") {
  53326. booleanString = "true";
  53327. }
  53328. return booleanString;
  53329. };
  53330. return AndOrNotEvaluator;
  53331. }());
  53332. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53333. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53334. })(BABYLON || (BABYLON = {}));
  53335. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53336. var BABYLON;
  53337. (function (BABYLON) {
  53338. var Database = /** @class */ (function () {
  53339. function Database(urlToScene, callbackManifestChecked) {
  53340. // Handling various flavors of prefixed version of IndexedDB
  53341. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53342. this.callbackManifestChecked = callbackManifestChecked;
  53343. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53344. this.db = null;
  53345. this._enableSceneOffline = false;
  53346. this._enableTexturesOffline = false;
  53347. this.manifestVersionFound = 0;
  53348. this.mustUpdateRessources = false;
  53349. this.hasReachedQuota = false;
  53350. if (!Database.IDBStorageEnabled) {
  53351. this.callbackManifestChecked(true);
  53352. }
  53353. else {
  53354. this.checkManifestFile();
  53355. }
  53356. }
  53357. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53358. get: function () {
  53359. return this._enableSceneOffline;
  53360. },
  53361. enumerable: true,
  53362. configurable: true
  53363. });
  53364. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53365. get: function () {
  53366. return this._enableTexturesOffline;
  53367. },
  53368. enumerable: true,
  53369. configurable: true
  53370. });
  53371. Database.prototype.checkManifestFile = function () {
  53372. var _this = this;
  53373. var noManifestFile = function () {
  53374. _this._enableSceneOffline = false;
  53375. _this._enableTexturesOffline = false;
  53376. _this.callbackManifestChecked(false);
  53377. };
  53378. var timeStampUsed = false;
  53379. var manifestURL = this.currentSceneUrl + ".manifest";
  53380. var xhr = new XMLHttpRequest();
  53381. if (navigator.onLine) {
  53382. // Adding a timestamp to by-pass browsers' cache
  53383. timeStampUsed = true;
  53384. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53385. }
  53386. xhr.open("GET", manifestURL, true);
  53387. xhr.addEventListener("load", function () {
  53388. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53389. try {
  53390. var manifestFile = JSON.parse(xhr.response);
  53391. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53392. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53393. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53394. _this.manifestVersionFound = manifestFile.version;
  53395. }
  53396. if (_this.callbackManifestChecked) {
  53397. _this.callbackManifestChecked(true);
  53398. }
  53399. }
  53400. catch (ex) {
  53401. noManifestFile();
  53402. }
  53403. }
  53404. else {
  53405. noManifestFile();
  53406. }
  53407. }, false);
  53408. xhr.addEventListener("error", function (event) {
  53409. if (timeStampUsed) {
  53410. timeStampUsed = false;
  53411. // Let's retry without the timeStamp
  53412. // It could fail when coupled with HTML5 Offline API
  53413. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53414. xhr.open("GET", retryManifestURL, true);
  53415. xhr.send();
  53416. }
  53417. else {
  53418. noManifestFile();
  53419. }
  53420. }, false);
  53421. try {
  53422. xhr.send();
  53423. }
  53424. catch (ex) {
  53425. BABYLON.Tools.Error("Error on XHR send request.");
  53426. this.callbackManifestChecked(false);
  53427. }
  53428. };
  53429. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53430. var _this = this;
  53431. var handleError = function () {
  53432. _this.isSupported = false;
  53433. if (errorCallback)
  53434. errorCallback();
  53435. };
  53436. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53437. // Your browser doesn't support IndexedDB
  53438. this.isSupported = false;
  53439. if (errorCallback)
  53440. errorCallback();
  53441. }
  53442. else {
  53443. // If the DB hasn't been opened or created yet
  53444. if (!this.db) {
  53445. this.hasReachedQuota = false;
  53446. this.isSupported = true;
  53447. var request = this.idbFactory.open("babylonjs", 1);
  53448. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53449. request.onerror = function (event) {
  53450. handleError();
  53451. };
  53452. // executes when a version change transaction cannot complete due to other active transactions
  53453. request.onblocked = function (event) {
  53454. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53455. handleError();
  53456. };
  53457. // DB has been opened successfully
  53458. request.onsuccess = function (event) {
  53459. _this.db = request.result;
  53460. successCallback();
  53461. };
  53462. // Initialization of the DB. Creating Scenes & Textures stores
  53463. request.onupgradeneeded = function (event) {
  53464. _this.db = (event.target).result;
  53465. if (_this.db) {
  53466. try {
  53467. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53468. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53469. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53470. }
  53471. catch (ex) {
  53472. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53473. handleError();
  53474. }
  53475. }
  53476. };
  53477. }
  53478. else {
  53479. if (successCallback)
  53480. successCallback();
  53481. }
  53482. }
  53483. };
  53484. Database.prototype.loadImageFromDB = function (url, image) {
  53485. var _this = this;
  53486. var completeURL = Database.ReturnFullUrlLocation(url);
  53487. var saveAndLoadImage = function () {
  53488. if (!_this.hasReachedQuota && _this.db !== null) {
  53489. // the texture is not yet in the DB, let's try to save it
  53490. _this._saveImageIntoDBAsync(completeURL, image);
  53491. }
  53492. else {
  53493. image.src = url;
  53494. }
  53495. };
  53496. if (!this.mustUpdateRessources) {
  53497. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53498. }
  53499. else {
  53500. saveAndLoadImage();
  53501. }
  53502. };
  53503. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53504. if (this.isSupported && this.db !== null) {
  53505. var texture;
  53506. var transaction = this.db.transaction(["textures"]);
  53507. transaction.onabort = function (event) {
  53508. image.src = url;
  53509. };
  53510. transaction.oncomplete = function (event) {
  53511. var blobTextureURL;
  53512. if (texture) {
  53513. var URL = window.URL || window.webkitURL;
  53514. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53515. image.onerror = function () {
  53516. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53517. image.src = url;
  53518. };
  53519. image.src = blobTextureURL;
  53520. }
  53521. else {
  53522. notInDBCallback();
  53523. }
  53524. };
  53525. var getRequest = transaction.objectStore("textures").get(url);
  53526. getRequest.onsuccess = function (event) {
  53527. texture = (event.target).result;
  53528. };
  53529. getRequest.onerror = function (event) {
  53530. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53531. image.src = url;
  53532. };
  53533. }
  53534. else {
  53535. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53536. image.src = url;
  53537. }
  53538. };
  53539. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53540. var _this = this;
  53541. if (this.isSupported) {
  53542. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53543. var generateBlobUrl = function () {
  53544. var blobTextureURL;
  53545. if (blob) {
  53546. var URL = window.URL || window.webkitURL;
  53547. try {
  53548. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53549. }
  53550. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53551. catch (ex) {
  53552. blobTextureURL = URL.createObjectURL(blob);
  53553. }
  53554. }
  53555. if (blobTextureURL) {
  53556. image.src = blobTextureURL;
  53557. }
  53558. };
  53559. if (Database.IsUASupportingBlobStorage) {
  53560. var xhr = new XMLHttpRequest(), blob;
  53561. xhr.open("GET", url, true);
  53562. xhr.responseType = "blob";
  53563. xhr.addEventListener("load", function () {
  53564. if (xhr.status === 200 && _this.db) {
  53565. // Blob as response (XHR2)
  53566. blob = xhr.response;
  53567. var transaction = _this.db.transaction(["textures"], "readwrite");
  53568. // the transaction could abort because of a QuotaExceededError error
  53569. transaction.onabort = function (event) {
  53570. try {
  53571. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53572. var srcElement = (event.srcElement || event.target);
  53573. var error = srcElement.error;
  53574. if (error && error.name === "QuotaExceededError") {
  53575. _this.hasReachedQuota = true;
  53576. }
  53577. }
  53578. catch (ex) { }
  53579. generateBlobUrl();
  53580. };
  53581. transaction.oncomplete = function (event) {
  53582. generateBlobUrl();
  53583. };
  53584. var newTexture = { textureUrl: url, data: blob };
  53585. try {
  53586. // Put the blob into the dabase
  53587. var addRequest = transaction.objectStore("textures").put(newTexture);
  53588. addRequest.onsuccess = function (event) {
  53589. };
  53590. addRequest.onerror = function (event) {
  53591. generateBlobUrl();
  53592. };
  53593. }
  53594. catch (ex) {
  53595. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53596. if (ex.code === 25) {
  53597. Database.IsUASupportingBlobStorage = false;
  53598. }
  53599. image.src = url;
  53600. }
  53601. }
  53602. else {
  53603. image.src = url;
  53604. }
  53605. }, false);
  53606. xhr.addEventListener("error", function (event) {
  53607. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53608. image.src = url;
  53609. }, false);
  53610. xhr.send();
  53611. }
  53612. else {
  53613. image.src = url;
  53614. }
  53615. }
  53616. else {
  53617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53618. image.src = url;
  53619. }
  53620. };
  53621. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53622. var _this = this;
  53623. var updateVersion = function () {
  53624. // the version is not yet in the DB or we need to update it
  53625. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53626. };
  53627. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53628. };
  53629. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53630. var _this = this;
  53631. if (this.isSupported && this.db) {
  53632. var version;
  53633. try {
  53634. var transaction = this.db.transaction(["versions"]);
  53635. transaction.oncomplete = function (event) {
  53636. if (version) {
  53637. // If the version in the JSON file is > than the version in DB
  53638. if (_this.manifestVersionFound > version.data) {
  53639. _this.mustUpdateRessources = true;
  53640. updateInDBCallback();
  53641. }
  53642. else {
  53643. callback(version.data);
  53644. }
  53645. }
  53646. else {
  53647. _this.mustUpdateRessources = true;
  53648. updateInDBCallback();
  53649. }
  53650. };
  53651. transaction.onabort = function (event) {
  53652. callback(-1);
  53653. };
  53654. var getRequest = transaction.objectStore("versions").get(url);
  53655. getRequest.onsuccess = function (event) {
  53656. version = (event.target).result;
  53657. };
  53658. getRequest.onerror = function (event) {
  53659. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53660. callback(-1);
  53661. };
  53662. }
  53663. catch (ex) {
  53664. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53665. callback(-1);
  53666. }
  53667. }
  53668. else {
  53669. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53670. callback(-1);
  53671. }
  53672. };
  53673. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53674. var _this = this;
  53675. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53676. try {
  53677. // Open a transaction to the database
  53678. var transaction = this.db.transaction(["versions"], "readwrite");
  53679. // the transaction could abort because of a QuotaExceededError error
  53680. transaction.onabort = function (event) {
  53681. try {
  53682. var error = event.srcElement['error'];
  53683. if (error && error.name === "QuotaExceededError") {
  53684. _this.hasReachedQuota = true;
  53685. }
  53686. }
  53687. catch (ex) { }
  53688. callback(-1);
  53689. };
  53690. transaction.oncomplete = function (event) {
  53691. callback(_this.manifestVersionFound);
  53692. };
  53693. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53694. // Put the scene into the database
  53695. var addRequest = transaction.objectStore("versions").put(newVersion);
  53696. addRequest.onsuccess = function (event) {
  53697. };
  53698. addRequest.onerror = function (event) {
  53699. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53700. };
  53701. }
  53702. catch (ex) {
  53703. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53704. callback(-1);
  53705. }
  53706. }
  53707. else {
  53708. callback(-1);
  53709. }
  53710. };
  53711. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53712. var _this = this;
  53713. var completeUrl = Database.ReturnFullUrlLocation(url);
  53714. var saveAndLoadFile = function () {
  53715. // the scene is not yet in the DB, let's try to save it
  53716. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53717. };
  53718. this._checkVersionFromDB(completeUrl, function (version) {
  53719. if (version !== -1) {
  53720. if (!_this.mustUpdateRessources) {
  53721. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53722. }
  53723. else {
  53724. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53725. }
  53726. }
  53727. else {
  53728. if (errorCallback) {
  53729. errorCallback();
  53730. }
  53731. }
  53732. });
  53733. };
  53734. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53735. if (this.isSupported && this.db) {
  53736. var targetStore;
  53737. if (url.indexOf(".babylon") !== -1) {
  53738. targetStore = "scenes";
  53739. }
  53740. else {
  53741. targetStore = "textures";
  53742. }
  53743. var file;
  53744. var transaction = this.db.transaction([targetStore]);
  53745. transaction.oncomplete = function (event) {
  53746. if (file) {
  53747. callback(file.data);
  53748. }
  53749. else {
  53750. notInDBCallback();
  53751. }
  53752. };
  53753. transaction.onabort = function (event) {
  53754. notInDBCallback();
  53755. };
  53756. var getRequest = transaction.objectStore(targetStore).get(url);
  53757. getRequest.onsuccess = function (event) {
  53758. file = (event.target).result;
  53759. };
  53760. getRequest.onerror = function (event) {
  53761. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53762. notInDBCallback();
  53763. };
  53764. }
  53765. else {
  53766. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53767. callback();
  53768. }
  53769. };
  53770. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53771. var _this = this;
  53772. if (this.isSupported) {
  53773. var targetStore;
  53774. if (url.indexOf(".babylon") !== -1) {
  53775. targetStore = "scenes";
  53776. }
  53777. else {
  53778. targetStore = "textures";
  53779. }
  53780. // Create XHR
  53781. var xhr = new XMLHttpRequest();
  53782. var fileData;
  53783. xhr.open("GET", url, true);
  53784. if (useArrayBuffer) {
  53785. xhr.responseType = "arraybuffer";
  53786. }
  53787. if (progressCallback) {
  53788. xhr.onprogress = progressCallback;
  53789. }
  53790. xhr.addEventListener("load", function () {
  53791. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53792. // Blob as response (XHR2)
  53793. //fileData = xhr.responseText;
  53794. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53795. if (!_this.hasReachedQuota && _this.db) {
  53796. // Open a transaction to the database
  53797. var transaction = _this.db.transaction([targetStore], "readwrite");
  53798. // the transaction could abort because of a QuotaExceededError error
  53799. transaction.onabort = function (event) {
  53800. try {
  53801. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53802. var error = event.srcElement['error'];
  53803. if (error && error.name === "QuotaExceededError") {
  53804. _this.hasReachedQuota = true;
  53805. }
  53806. }
  53807. catch (ex) { }
  53808. callback(fileData);
  53809. };
  53810. transaction.oncomplete = function (event) {
  53811. callback(fileData);
  53812. };
  53813. var newFile;
  53814. if (targetStore === "scenes") {
  53815. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53816. }
  53817. else {
  53818. newFile = { textureUrl: url, data: fileData };
  53819. }
  53820. try {
  53821. // Put the scene into the database
  53822. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53823. addRequest.onsuccess = function (event) {
  53824. };
  53825. addRequest.onerror = function (event) {
  53826. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53827. };
  53828. }
  53829. catch (ex) {
  53830. callback(fileData);
  53831. }
  53832. }
  53833. else {
  53834. callback(fileData);
  53835. }
  53836. }
  53837. else {
  53838. callback();
  53839. }
  53840. }, false);
  53841. xhr.addEventListener("error", function (event) {
  53842. BABYLON.Tools.Error("error on XHR request.");
  53843. callback();
  53844. }, false);
  53845. xhr.send();
  53846. }
  53847. else {
  53848. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53849. callback();
  53850. }
  53851. };
  53852. Database.IsUASupportingBlobStorage = true;
  53853. Database.IDBStorageEnabled = true;
  53854. Database.parseURL = function (url) {
  53855. var a = document.createElement('a');
  53856. a.href = url;
  53857. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53858. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53859. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53860. return absLocation;
  53861. };
  53862. Database.ReturnFullUrlLocation = function (url) {
  53863. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53864. return (Database.parseURL(window.location.href) + url);
  53865. }
  53866. else {
  53867. return url;
  53868. }
  53869. };
  53870. return Database;
  53871. }());
  53872. BABYLON.Database = Database;
  53873. })(BABYLON || (BABYLON = {}));
  53874. //# sourceMappingURL=babylon.database.js.map
  53875. var BABYLON;
  53876. (function (BABYLON) {
  53877. var FresnelParameters = /** @class */ (function () {
  53878. function FresnelParameters() {
  53879. this._isEnabled = true;
  53880. this.leftColor = BABYLON.Color3.White();
  53881. this.rightColor = BABYLON.Color3.Black();
  53882. this.bias = 0;
  53883. this.power = 1;
  53884. }
  53885. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53886. get: function () {
  53887. return this._isEnabled;
  53888. },
  53889. set: function (value) {
  53890. if (this._isEnabled === value) {
  53891. return;
  53892. }
  53893. this._isEnabled = value;
  53894. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53895. },
  53896. enumerable: true,
  53897. configurable: true
  53898. });
  53899. FresnelParameters.prototype.clone = function () {
  53900. var newFresnelParameters = new FresnelParameters();
  53901. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53902. return newFresnelParameters;
  53903. };
  53904. FresnelParameters.prototype.serialize = function () {
  53905. var serializationObject = {};
  53906. serializationObject.isEnabled = this.isEnabled;
  53907. serializationObject.leftColor = this.leftColor;
  53908. serializationObject.rightColor = this.rightColor;
  53909. serializationObject.bias = this.bias;
  53910. serializationObject.power = this.power;
  53911. return serializationObject;
  53912. };
  53913. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53914. var fresnelParameters = new FresnelParameters();
  53915. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53916. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53917. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53918. fresnelParameters.bias = parsedFresnelParameters.bias;
  53919. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53920. return fresnelParameters;
  53921. };
  53922. return FresnelParameters;
  53923. }());
  53924. BABYLON.FresnelParameters = FresnelParameters;
  53925. })(BABYLON || (BABYLON = {}));
  53926. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53927. var BABYLON;
  53928. (function (BABYLON) {
  53929. var MultiMaterial = /** @class */ (function (_super) {
  53930. __extends(MultiMaterial, _super);
  53931. function MultiMaterial(name, scene) {
  53932. var _this = _super.call(this, name, scene, true) || this;
  53933. scene.multiMaterials.push(_this);
  53934. _this.subMaterials = new Array();
  53935. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53936. return _this;
  53937. }
  53938. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53939. get: function () {
  53940. return this._subMaterials;
  53941. },
  53942. set: function (value) {
  53943. this._subMaterials = value;
  53944. this._hookArray(value);
  53945. },
  53946. enumerable: true,
  53947. configurable: true
  53948. });
  53949. MultiMaterial.prototype._hookArray = function (array) {
  53950. var _this = this;
  53951. var oldPush = array.push;
  53952. array.push = function () {
  53953. var items = [];
  53954. for (var _i = 0; _i < arguments.length; _i++) {
  53955. items[_i] = arguments[_i];
  53956. }
  53957. var result = oldPush.apply(array, items);
  53958. _this._markAllSubMeshesAsTexturesDirty();
  53959. return result;
  53960. };
  53961. var oldSplice = array.splice;
  53962. array.splice = function (index, deleteCount) {
  53963. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53964. _this._markAllSubMeshesAsTexturesDirty();
  53965. return deleted;
  53966. };
  53967. };
  53968. // Properties
  53969. MultiMaterial.prototype.getSubMaterial = function (index) {
  53970. if (index < 0 || index >= this.subMaterials.length) {
  53971. return this.getScene().defaultMaterial;
  53972. }
  53973. return this.subMaterials[index];
  53974. };
  53975. MultiMaterial.prototype.getActiveTextures = function () {
  53976. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53977. if (subMaterial) {
  53978. return subMaterial.getActiveTextures();
  53979. }
  53980. else {
  53981. return [];
  53982. }
  53983. }));
  53984. var _a;
  53985. };
  53986. // Methods
  53987. MultiMaterial.prototype.getClassName = function () {
  53988. return "MultiMaterial";
  53989. };
  53990. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53991. for (var index = 0; index < this.subMaterials.length; index++) {
  53992. var subMaterial = this.subMaterials[index];
  53993. if (subMaterial) {
  53994. if (subMaterial.storeEffectOnSubMeshes) {
  53995. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53996. return false;
  53997. }
  53998. continue;
  53999. }
  54000. if (!subMaterial.isReady(mesh)) {
  54001. return false;
  54002. }
  54003. }
  54004. }
  54005. return true;
  54006. };
  54007. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54008. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54009. for (var index = 0; index < this.subMaterials.length; index++) {
  54010. var subMaterial = null;
  54011. var current = this.subMaterials[index];
  54012. if (cloneChildren && current) {
  54013. subMaterial = current.clone(name + "-" + current.name);
  54014. }
  54015. else {
  54016. subMaterial = this.subMaterials[index];
  54017. }
  54018. newMultiMaterial.subMaterials.push(subMaterial);
  54019. }
  54020. return newMultiMaterial;
  54021. };
  54022. MultiMaterial.prototype.serialize = function () {
  54023. var serializationObject = {};
  54024. serializationObject.name = this.name;
  54025. serializationObject.id = this.id;
  54026. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54027. serializationObject.materials = [];
  54028. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54029. var subMat = this.subMaterials[matIndex];
  54030. if (subMat) {
  54031. serializationObject.materials.push(subMat.id);
  54032. }
  54033. else {
  54034. serializationObject.materials.push(null);
  54035. }
  54036. }
  54037. return serializationObject;
  54038. };
  54039. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54040. var scene = this.getScene();
  54041. if (!scene) {
  54042. return;
  54043. }
  54044. var index = scene.multiMaterials.indexOf(this);
  54045. if (index >= 0) {
  54046. scene.multiMaterials.splice(index, 1);
  54047. }
  54048. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54049. };
  54050. return MultiMaterial;
  54051. }(BABYLON.Material));
  54052. BABYLON.MultiMaterial = MultiMaterial;
  54053. })(BABYLON || (BABYLON = {}));
  54054. //# sourceMappingURL=babylon.multiMaterial.js.map
  54055. var BABYLON;
  54056. (function (BABYLON) {
  54057. var FreeCameraTouchInput = /** @class */ (function () {
  54058. function FreeCameraTouchInput() {
  54059. this._offsetX = null;
  54060. this._offsetY = null;
  54061. this._pointerCount = 0;
  54062. this._pointerPressed = new Array();
  54063. this.touchAngularSensibility = 200000.0;
  54064. this.touchMoveSensibility = 250.0;
  54065. }
  54066. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54067. var _this = this;
  54068. var previousPosition = null;
  54069. if (this._pointerInput === undefined) {
  54070. this._onLostFocus = function (evt) {
  54071. _this._offsetX = null;
  54072. _this._offsetY = null;
  54073. };
  54074. this._pointerInput = function (p, s) {
  54075. var evt = p.event;
  54076. if (evt.pointerType === "mouse") {
  54077. return;
  54078. }
  54079. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54080. if (!noPreventDefault) {
  54081. evt.preventDefault();
  54082. }
  54083. _this._pointerPressed.push(evt.pointerId);
  54084. if (_this._pointerPressed.length !== 1) {
  54085. return;
  54086. }
  54087. previousPosition = {
  54088. x: evt.clientX,
  54089. y: evt.clientY
  54090. };
  54091. }
  54092. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54093. if (!noPreventDefault) {
  54094. evt.preventDefault();
  54095. }
  54096. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54097. if (index === -1) {
  54098. return;
  54099. }
  54100. _this._pointerPressed.splice(index, 1);
  54101. if (index != 0) {
  54102. return;
  54103. }
  54104. previousPosition = null;
  54105. _this._offsetX = null;
  54106. _this._offsetY = null;
  54107. }
  54108. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54109. if (!noPreventDefault) {
  54110. evt.preventDefault();
  54111. }
  54112. if (!previousPosition) {
  54113. return;
  54114. }
  54115. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54116. if (index != 0) {
  54117. return;
  54118. }
  54119. _this._offsetX = evt.clientX - previousPosition.x;
  54120. _this._offsetY = -(evt.clientY - previousPosition.y);
  54121. }
  54122. };
  54123. }
  54124. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54125. if (this._onLostFocus) {
  54126. element.addEventListener("blur", this._onLostFocus);
  54127. }
  54128. };
  54129. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54130. if (this._pointerInput && element) {
  54131. if (this._observer) {
  54132. this.camera.getScene().onPointerObservable.remove(this._observer);
  54133. this._observer = null;
  54134. }
  54135. if (this._onLostFocus) {
  54136. element.removeEventListener("blur", this._onLostFocus);
  54137. this._onLostFocus = null;
  54138. }
  54139. this._pointerPressed = [];
  54140. this._offsetX = null;
  54141. this._offsetY = null;
  54142. this._pointerCount = 0;
  54143. }
  54144. };
  54145. FreeCameraTouchInput.prototype.checkInputs = function () {
  54146. if (this._offsetX && this._offsetY) {
  54147. var camera = this.camera;
  54148. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54149. if (this._pointerPressed.length > 1) {
  54150. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54151. }
  54152. else {
  54153. var speed = camera._computeLocalCameraSpeed();
  54154. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54155. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54156. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54157. }
  54158. }
  54159. };
  54160. FreeCameraTouchInput.prototype.getClassName = function () {
  54161. return "FreeCameraTouchInput";
  54162. };
  54163. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54164. return "touch";
  54165. };
  54166. __decorate([
  54167. BABYLON.serialize()
  54168. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54169. __decorate([
  54170. BABYLON.serialize()
  54171. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54172. return FreeCameraTouchInput;
  54173. }());
  54174. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54175. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54176. })(BABYLON || (BABYLON = {}));
  54177. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54178. var BABYLON;
  54179. (function (BABYLON) {
  54180. // We're mainly based on the logic defined into the FreeCamera code
  54181. var TouchCamera = /** @class */ (function (_super) {
  54182. __extends(TouchCamera, _super);
  54183. //-- end properties for backward compatibility for inputs
  54184. function TouchCamera(name, position, scene) {
  54185. var _this = _super.call(this, name, position, scene) || this;
  54186. _this.inputs.addTouch();
  54187. _this._setupInputs();
  54188. return _this;
  54189. }
  54190. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54191. //-- Begin properties for backward compatibility for inputs
  54192. get: function () {
  54193. var touch = this.inputs.attached["touch"];
  54194. if (touch)
  54195. return touch.touchAngularSensibility;
  54196. return 0;
  54197. },
  54198. set: function (value) {
  54199. var touch = this.inputs.attached["touch"];
  54200. if (touch)
  54201. touch.touchAngularSensibility = value;
  54202. },
  54203. enumerable: true,
  54204. configurable: true
  54205. });
  54206. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54207. get: function () {
  54208. var touch = this.inputs.attached["touch"];
  54209. if (touch)
  54210. return touch.touchMoveSensibility;
  54211. return 0;
  54212. },
  54213. set: function (value) {
  54214. var touch = this.inputs.attached["touch"];
  54215. if (touch)
  54216. touch.touchMoveSensibility = value;
  54217. },
  54218. enumerable: true,
  54219. configurable: true
  54220. });
  54221. TouchCamera.prototype.getClassName = function () {
  54222. return "TouchCamera";
  54223. };
  54224. TouchCamera.prototype._setupInputs = function () {
  54225. var mouse = this.inputs.attached["mouse"];
  54226. if (mouse) {
  54227. mouse.touchEnabled = false;
  54228. }
  54229. };
  54230. return TouchCamera;
  54231. }(BABYLON.FreeCamera));
  54232. BABYLON.TouchCamera = TouchCamera;
  54233. })(BABYLON || (BABYLON = {}));
  54234. //# sourceMappingURL=babylon.touchCamera.js.map
  54235. var BABYLON;
  54236. (function (BABYLON) {
  54237. var ProceduralTexture = /** @class */ (function (_super) {
  54238. __extends(ProceduralTexture, _super);
  54239. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54240. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54241. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54242. if (isCube === void 0) { isCube = false; }
  54243. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54244. _this.isCube = isCube;
  54245. _this.isEnabled = true;
  54246. _this._currentRefreshId = -1;
  54247. _this._refreshRate = 1;
  54248. _this._vertexBuffers = {};
  54249. _this._uniforms = new Array();
  54250. _this._samplers = new Array();
  54251. _this._textures = {};
  54252. _this._floats = {};
  54253. _this._floatsArrays = {};
  54254. _this._colors3 = {};
  54255. _this._colors4 = {};
  54256. _this._vectors2 = {};
  54257. _this._vectors3 = {};
  54258. _this._matrices = {};
  54259. _this._fallbackTextureUsed = false;
  54260. scene._proceduralTextures.push(_this);
  54261. _this._engine = scene.getEngine();
  54262. _this.name = name;
  54263. _this.isRenderTarget = true;
  54264. _this._size = size;
  54265. _this._generateMipMaps = generateMipMaps;
  54266. _this.setFragment(fragment);
  54267. _this._fallbackTexture = fallbackTexture;
  54268. if (isCube) {
  54269. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54270. _this.setFloat("face", 0);
  54271. }
  54272. else {
  54273. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54274. }
  54275. // VBO
  54276. var vertices = [];
  54277. vertices.push(1, 1);
  54278. vertices.push(-1, 1);
  54279. vertices.push(-1, -1);
  54280. vertices.push(1, -1);
  54281. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54282. _this._createIndexBuffer();
  54283. return _this;
  54284. }
  54285. ProceduralTexture.prototype._createIndexBuffer = function () {
  54286. var engine = this._engine;
  54287. // Indices
  54288. var indices = [];
  54289. indices.push(0);
  54290. indices.push(1);
  54291. indices.push(2);
  54292. indices.push(0);
  54293. indices.push(2);
  54294. indices.push(3);
  54295. this._indexBuffer = engine.createIndexBuffer(indices);
  54296. };
  54297. ProceduralTexture.prototype._rebuild = function () {
  54298. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54299. if (vb) {
  54300. vb._rebuild();
  54301. }
  54302. this._createIndexBuffer();
  54303. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54304. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54305. }
  54306. };
  54307. ProceduralTexture.prototype.reset = function () {
  54308. if (this._effect === undefined) {
  54309. return;
  54310. }
  54311. var engine = this._engine;
  54312. engine._releaseEffect(this._effect);
  54313. };
  54314. ProceduralTexture.prototype.isReady = function () {
  54315. var _this = this;
  54316. var engine = this._engine;
  54317. var shaders;
  54318. if (!this._fragment) {
  54319. return false;
  54320. }
  54321. if (this._fallbackTextureUsed) {
  54322. return true;
  54323. }
  54324. if (this._fragment.fragmentElement !== undefined) {
  54325. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54326. }
  54327. else {
  54328. shaders = { vertex: "procedural", fragment: this._fragment };
  54329. }
  54330. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54331. _this.releaseInternalTexture();
  54332. if (_this._fallbackTexture) {
  54333. _this._texture = _this._fallbackTexture._texture;
  54334. if (_this._texture) {
  54335. _this._texture.incrementReferences();
  54336. }
  54337. }
  54338. _this._fallbackTextureUsed = true;
  54339. });
  54340. return this._effect.isReady();
  54341. };
  54342. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54343. this._currentRefreshId = -1;
  54344. };
  54345. ProceduralTexture.prototype.setFragment = function (fragment) {
  54346. this._fragment = fragment;
  54347. };
  54348. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54349. get: function () {
  54350. return this._refreshRate;
  54351. },
  54352. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54353. set: function (value) {
  54354. this._refreshRate = value;
  54355. this.resetRefreshCounter();
  54356. },
  54357. enumerable: true,
  54358. configurable: true
  54359. });
  54360. ProceduralTexture.prototype._shouldRender = function () {
  54361. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54362. return false;
  54363. }
  54364. if (this._fallbackTextureUsed) {
  54365. return false;
  54366. }
  54367. if (this._currentRefreshId === -1) {
  54368. this._currentRefreshId = 1;
  54369. return true;
  54370. }
  54371. if (this.refreshRate === this._currentRefreshId) {
  54372. this._currentRefreshId = 1;
  54373. return true;
  54374. }
  54375. this._currentRefreshId++;
  54376. return false;
  54377. };
  54378. ProceduralTexture.prototype.getRenderSize = function () {
  54379. return this._size;
  54380. };
  54381. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54382. if (this._fallbackTextureUsed) {
  54383. return;
  54384. }
  54385. this.releaseInternalTexture();
  54386. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54387. };
  54388. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54389. if (this._uniforms.indexOf(uniformName) === -1) {
  54390. this._uniforms.push(uniformName);
  54391. }
  54392. };
  54393. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54394. if (this._samplers.indexOf(name) === -1) {
  54395. this._samplers.push(name);
  54396. }
  54397. this._textures[name] = texture;
  54398. return this;
  54399. };
  54400. ProceduralTexture.prototype.setFloat = function (name, value) {
  54401. this._checkUniform(name);
  54402. this._floats[name] = value;
  54403. return this;
  54404. };
  54405. ProceduralTexture.prototype.setFloats = function (name, value) {
  54406. this._checkUniform(name);
  54407. this._floatsArrays[name] = value;
  54408. return this;
  54409. };
  54410. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54411. this._checkUniform(name);
  54412. this._colors3[name] = value;
  54413. return this;
  54414. };
  54415. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54416. this._checkUniform(name);
  54417. this._colors4[name] = value;
  54418. return this;
  54419. };
  54420. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54421. this._checkUniform(name);
  54422. this._vectors2[name] = value;
  54423. return this;
  54424. };
  54425. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54426. this._checkUniform(name);
  54427. this._vectors3[name] = value;
  54428. return this;
  54429. };
  54430. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54431. this._checkUniform(name);
  54432. this._matrices[name] = value;
  54433. return this;
  54434. };
  54435. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54436. var scene = this.getScene();
  54437. if (!scene) {
  54438. return;
  54439. }
  54440. var engine = this._engine;
  54441. // Render
  54442. engine.enableEffect(this._effect);
  54443. engine.setState(false);
  54444. // Texture
  54445. for (var name in this._textures) {
  54446. this._effect.setTexture(name, this._textures[name]);
  54447. }
  54448. // Float
  54449. for (name in this._floats) {
  54450. this._effect.setFloat(name, this._floats[name]);
  54451. }
  54452. // Floats
  54453. for (name in this._floatsArrays) {
  54454. this._effect.setArray(name, this._floatsArrays[name]);
  54455. }
  54456. // Color3
  54457. for (name in this._colors3) {
  54458. this._effect.setColor3(name, this._colors3[name]);
  54459. }
  54460. // Color4
  54461. for (name in this._colors4) {
  54462. var color = this._colors4[name];
  54463. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54464. }
  54465. // Vector2
  54466. for (name in this._vectors2) {
  54467. this._effect.setVector2(name, this._vectors2[name]);
  54468. }
  54469. // Vector3
  54470. for (name in this._vectors3) {
  54471. this._effect.setVector3(name, this._vectors3[name]);
  54472. }
  54473. // Matrix
  54474. for (name in this._matrices) {
  54475. this._effect.setMatrix(name, this._matrices[name]);
  54476. }
  54477. if (!this._texture) {
  54478. return;
  54479. }
  54480. if (this.isCube) {
  54481. for (var face = 0; face < 6; face++) {
  54482. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54483. // VBOs
  54484. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54485. this._effect.setFloat("face", face);
  54486. // Clear
  54487. engine.clear(scene.clearColor, true, true, true);
  54488. // Draw order
  54489. engine.draw(true, 0, 6);
  54490. // Mipmaps
  54491. if (face === 5) {
  54492. engine.generateMipMapsForCubemap(this._texture);
  54493. }
  54494. }
  54495. }
  54496. else {
  54497. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54498. // VBOs
  54499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54500. // Clear
  54501. engine.clear(scene.clearColor, true, true, true);
  54502. // Draw order
  54503. engine.draw(true, 0, 6);
  54504. }
  54505. // Unbind
  54506. engine.unBindFramebuffer(this._texture, this.isCube);
  54507. if (this.onGenerated) {
  54508. this.onGenerated();
  54509. }
  54510. };
  54511. ProceduralTexture.prototype.clone = function () {
  54512. var textureSize = this.getSize();
  54513. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54514. // Base texture
  54515. newTexture.hasAlpha = this.hasAlpha;
  54516. newTexture.level = this.level;
  54517. // RenderTarget Texture
  54518. newTexture.coordinatesMode = this.coordinatesMode;
  54519. return newTexture;
  54520. };
  54521. ProceduralTexture.prototype.dispose = function () {
  54522. var scene = this.getScene();
  54523. if (!scene) {
  54524. return;
  54525. }
  54526. var index = scene._proceduralTextures.indexOf(this);
  54527. if (index >= 0) {
  54528. scene._proceduralTextures.splice(index, 1);
  54529. }
  54530. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54531. if (vertexBuffer) {
  54532. vertexBuffer.dispose();
  54533. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54534. }
  54535. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54536. this._indexBuffer = null;
  54537. }
  54538. _super.prototype.dispose.call(this);
  54539. };
  54540. return ProceduralTexture;
  54541. }(BABYLON.Texture));
  54542. BABYLON.ProceduralTexture = ProceduralTexture;
  54543. })(BABYLON || (BABYLON = {}));
  54544. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54545. var BABYLON;
  54546. (function (BABYLON) {
  54547. var CustomProceduralTexture = /** @class */ (function (_super) {
  54548. __extends(CustomProceduralTexture, _super);
  54549. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54550. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54551. _this._animate = true;
  54552. _this._time = 0;
  54553. _this._texturePath = texturePath;
  54554. //Try to load json
  54555. _this.loadJson(texturePath);
  54556. _this.refreshRate = 1;
  54557. return _this;
  54558. }
  54559. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54560. var _this = this;
  54561. var noConfigFile = function () {
  54562. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54563. try {
  54564. _this.setFragment(_this._texturePath);
  54565. }
  54566. catch (ex) {
  54567. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54568. }
  54569. };
  54570. var configFileUrl = jsonUrl + "/config.json";
  54571. var xhr = new XMLHttpRequest();
  54572. xhr.open("GET", configFileUrl, true);
  54573. xhr.addEventListener("load", function () {
  54574. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54575. try {
  54576. _this._config = JSON.parse(xhr.response);
  54577. _this.updateShaderUniforms();
  54578. _this.updateTextures();
  54579. _this.setFragment(_this._texturePath + "/custom");
  54580. _this._animate = _this._config.animate;
  54581. _this.refreshRate = _this._config.refreshrate;
  54582. }
  54583. catch (ex) {
  54584. noConfigFile();
  54585. }
  54586. }
  54587. else {
  54588. noConfigFile();
  54589. }
  54590. }, false);
  54591. xhr.addEventListener("error", function () {
  54592. noConfigFile();
  54593. }, false);
  54594. try {
  54595. xhr.send();
  54596. }
  54597. catch (ex) {
  54598. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54599. }
  54600. };
  54601. CustomProceduralTexture.prototype.isReady = function () {
  54602. if (!_super.prototype.isReady.call(this)) {
  54603. return false;
  54604. }
  54605. for (var name in this._textures) {
  54606. var texture = this._textures[name];
  54607. if (!texture.isReady()) {
  54608. return false;
  54609. }
  54610. }
  54611. return true;
  54612. };
  54613. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54614. var scene = this.getScene();
  54615. if (this._animate && scene) {
  54616. this._time += scene.getAnimationRatio() * 0.03;
  54617. this.updateShaderUniforms();
  54618. }
  54619. _super.prototype.render.call(this, useCameraPostProcess);
  54620. };
  54621. CustomProceduralTexture.prototype.updateTextures = function () {
  54622. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54623. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54624. }
  54625. };
  54626. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54627. if (this._config) {
  54628. for (var j = 0; j < this._config.uniforms.length; j++) {
  54629. var uniform = this._config.uniforms[j];
  54630. switch (uniform.type) {
  54631. case "float":
  54632. this.setFloat(uniform.name, uniform.value);
  54633. break;
  54634. case "color3":
  54635. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54636. break;
  54637. case "color4":
  54638. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54639. break;
  54640. case "vector2":
  54641. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54642. break;
  54643. case "vector3":
  54644. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54645. break;
  54646. }
  54647. }
  54648. }
  54649. this.setFloat("time", this._time);
  54650. };
  54651. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54652. get: function () {
  54653. return this._animate;
  54654. },
  54655. set: function (value) {
  54656. this._animate = value;
  54657. },
  54658. enumerable: true,
  54659. configurable: true
  54660. });
  54661. return CustomProceduralTexture;
  54662. }(BABYLON.ProceduralTexture));
  54663. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54664. })(BABYLON || (BABYLON = {}));
  54665. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54666. var BABYLON;
  54667. (function (BABYLON) {
  54668. var FreeCameraGamepadInput = /** @class */ (function () {
  54669. function FreeCameraGamepadInput() {
  54670. this.gamepadAngularSensibility = 200;
  54671. this.gamepadMoveSensibility = 40;
  54672. // private members
  54673. this._cameraTransform = BABYLON.Matrix.Identity();
  54674. this._deltaTransform = BABYLON.Vector3.Zero();
  54675. this._vector3 = BABYLON.Vector3.Zero();
  54676. this._vector2 = BABYLON.Vector2.Zero();
  54677. }
  54678. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54679. var _this = this;
  54680. var manager = this.camera.getScene().gamepadManager;
  54681. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54682. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54683. // prioritize XBOX gamepads.
  54684. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54685. _this.gamepad = gamepad;
  54686. }
  54687. }
  54688. });
  54689. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54690. if (_this.gamepad === gamepad) {
  54691. _this.gamepad = null;
  54692. }
  54693. });
  54694. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54695. };
  54696. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54697. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54698. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54699. this.gamepad = null;
  54700. };
  54701. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54702. if (this.gamepad && this.gamepad.leftStick) {
  54703. var camera = this.camera;
  54704. var LSValues = this.gamepad.leftStick;
  54705. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54706. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54707. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54708. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54709. var RSValues = this.gamepad.rightStick;
  54710. if (RSValues) {
  54711. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54712. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54713. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54714. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54715. }
  54716. else {
  54717. RSValues = { x: 0, y: 0 };
  54718. }
  54719. if (!camera.rotationQuaternion) {
  54720. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54721. }
  54722. else {
  54723. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54724. }
  54725. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54726. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54727. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54728. camera.cameraDirection.addInPlace(this._deltaTransform);
  54729. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54730. camera.cameraRotation.addInPlace(this._vector2);
  54731. }
  54732. };
  54733. FreeCameraGamepadInput.prototype.getClassName = function () {
  54734. return "FreeCameraGamepadInput";
  54735. };
  54736. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54737. return "gamepad";
  54738. };
  54739. __decorate([
  54740. BABYLON.serialize()
  54741. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54742. __decorate([
  54743. BABYLON.serialize()
  54744. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54745. return FreeCameraGamepadInput;
  54746. }());
  54747. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54748. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54749. })(BABYLON || (BABYLON = {}));
  54750. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54751. var BABYLON;
  54752. (function (BABYLON) {
  54753. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54754. function ArcRotateCameraGamepadInput() {
  54755. this.gamepadRotationSensibility = 80;
  54756. this.gamepadMoveSensibility = 40;
  54757. }
  54758. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54759. var _this = this;
  54760. var manager = this.camera.getScene().gamepadManager;
  54761. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54762. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54763. // prioritize XBOX gamepads.
  54764. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54765. _this.gamepad = gamepad;
  54766. }
  54767. }
  54768. });
  54769. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54770. if (_this.gamepad === gamepad) {
  54771. _this.gamepad = null;
  54772. }
  54773. });
  54774. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54775. };
  54776. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54777. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54778. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54779. this.gamepad = null;
  54780. };
  54781. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54782. if (this.gamepad) {
  54783. var camera = this.camera;
  54784. var RSValues = this.gamepad.rightStick;
  54785. if (RSValues) {
  54786. if (RSValues.x != 0) {
  54787. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54788. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54789. camera.inertialAlphaOffset += normalizedRX;
  54790. }
  54791. }
  54792. if (RSValues.y != 0) {
  54793. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54794. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54795. camera.inertialBetaOffset += normalizedRY;
  54796. }
  54797. }
  54798. }
  54799. var LSValues = this.gamepad.leftStick;
  54800. if (LSValues && LSValues.y != 0) {
  54801. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54802. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54803. this.camera.inertialRadiusOffset -= normalizedLY;
  54804. }
  54805. }
  54806. }
  54807. };
  54808. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54809. return "ArcRotateCameraGamepadInput";
  54810. };
  54811. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54812. return "gamepad";
  54813. };
  54814. __decorate([
  54815. BABYLON.serialize()
  54816. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54817. __decorate([
  54818. BABYLON.serialize()
  54819. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54820. return ArcRotateCameraGamepadInput;
  54821. }());
  54822. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54823. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54824. })(BABYLON || (BABYLON = {}));
  54825. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54826. var BABYLON;
  54827. (function (BABYLON) {
  54828. var GamepadManager = /** @class */ (function () {
  54829. function GamepadManager() {
  54830. var _this = this;
  54831. this._babylonGamepads = [];
  54832. this._oneGamepadConnected = false;
  54833. this._isMonitoring = false;
  54834. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54835. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54836. this._gamepadEventSupported = false;
  54837. }
  54838. else {
  54839. this._gamepadEventSupported = 'GamepadEvent' in window;
  54840. this._gamepadSupport = (navigator.getGamepads ||
  54841. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54842. }
  54843. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54844. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54845. for (var i in _this._babylonGamepads) {
  54846. var gamepad = _this._babylonGamepads[i];
  54847. if (gamepad && gamepad._isConnected) {
  54848. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54849. }
  54850. }
  54851. });
  54852. this._onGamepadConnectedEvent = function (evt) {
  54853. var gamepad = evt.gamepad;
  54854. if (gamepad.index in _this._babylonGamepads) {
  54855. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54856. return;
  54857. }
  54858. }
  54859. var newGamepad;
  54860. if (_this._babylonGamepads[gamepad.index]) {
  54861. newGamepad = _this._babylonGamepads[gamepad.index];
  54862. newGamepad.browserGamepad = gamepad;
  54863. newGamepad._isConnected = true;
  54864. }
  54865. else {
  54866. newGamepad = _this._addNewGamepad(gamepad);
  54867. }
  54868. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54869. _this._startMonitoringGamepads();
  54870. };
  54871. this._onGamepadDisconnectedEvent = function (evt) {
  54872. var gamepad = evt.gamepad;
  54873. // Remove the gamepad from the list of gamepads to monitor.
  54874. for (var i in _this._babylonGamepads) {
  54875. if (_this._babylonGamepads[i].index === gamepad.index) {
  54876. var disconnectedGamepad = _this._babylonGamepads[i];
  54877. disconnectedGamepad._isConnected = false;
  54878. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54879. break;
  54880. }
  54881. }
  54882. };
  54883. if (this._gamepadSupport) {
  54884. //first add already-connected gamepads
  54885. this._updateGamepadObjects();
  54886. if (this._babylonGamepads.length) {
  54887. this._startMonitoringGamepads();
  54888. }
  54889. // Checking if the gamepad connected event is supported (like in Firefox)
  54890. if (this._gamepadEventSupported) {
  54891. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54892. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54893. }
  54894. else {
  54895. this._startMonitoringGamepads();
  54896. }
  54897. }
  54898. }
  54899. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54900. get: function () {
  54901. return this._babylonGamepads;
  54902. },
  54903. enumerable: true,
  54904. configurable: true
  54905. });
  54906. GamepadManager.prototype.getGamepadByType = function (type) {
  54907. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54908. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54909. var gamepad = _a[_i];
  54910. if (gamepad && gamepad.type === type) {
  54911. return gamepad;
  54912. }
  54913. }
  54914. return null;
  54915. };
  54916. GamepadManager.prototype.dispose = function () {
  54917. if (this._gamepadEventSupported) {
  54918. if (this._onGamepadConnectedEvent) {
  54919. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54920. }
  54921. if (this._onGamepadDisconnectedEvent) {
  54922. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54923. }
  54924. this._onGamepadConnectedEvent = null;
  54925. this._onGamepadDisconnectedEvent = null;
  54926. }
  54927. this._babylonGamepads.forEach(function (gamepad) {
  54928. gamepad.dispose();
  54929. });
  54930. this.onGamepadConnectedObservable.clear();
  54931. this.onGamepadDisconnectedObservable.clear();
  54932. this._oneGamepadConnected = false;
  54933. this._stopMonitoringGamepads();
  54934. this._babylonGamepads = [];
  54935. };
  54936. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54937. if (!this._oneGamepadConnected) {
  54938. this._oneGamepadConnected = true;
  54939. }
  54940. var newGamepad;
  54941. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54942. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54943. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54944. }
  54945. else if (gamepad.pose) {
  54946. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54947. }
  54948. else {
  54949. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54950. }
  54951. this._babylonGamepads[newGamepad.index] = newGamepad;
  54952. return newGamepad;
  54953. };
  54954. GamepadManager.prototype._startMonitoringGamepads = function () {
  54955. if (!this._isMonitoring) {
  54956. this._isMonitoring = true;
  54957. this._checkGamepadsStatus();
  54958. }
  54959. };
  54960. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54961. this._isMonitoring = false;
  54962. };
  54963. GamepadManager.prototype._checkGamepadsStatus = function () {
  54964. var _this = this;
  54965. // Hack to be compatible Chrome
  54966. this._updateGamepadObjects();
  54967. for (var i in this._babylonGamepads) {
  54968. var gamepad = this._babylonGamepads[i];
  54969. if (!gamepad || !gamepad.isConnected) {
  54970. continue;
  54971. }
  54972. gamepad.update();
  54973. }
  54974. if (this._isMonitoring) {
  54975. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54976. }
  54977. };
  54978. // This function is called only on Chrome, which does not properly support
  54979. // connection/disconnection events and forces you to recopy again the gamepad object
  54980. GamepadManager.prototype._updateGamepadObjects = function () {
  54981. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54982. for (var i = 0; i < gamepads.length; i++) {
  54983. if (gamepads[i]) {
  54984. if (!this._babylonGamepads[gamepads[i].index]) {
  54985. var newGamepad = this._addNewGamepad(gamepads[i]);
  54986. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54987. }
  54988. else {
  54989. // Forced to copy again this object for Chrome for unknown reason
  54990. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54991. if (!this._babylonGamepads[i].isConnected) {
  54992. this._babylonGamepads[i]._isConnected = true;
  54993. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54994. }
  54995. }
  54996. }
  54997. }
  54998. };
  54999. return GamepadManager;
  55000. }());
  55001. BABYLON.GamepadManager = GamepadManager;
  55002. })(BABYLON || (BABYLON = {}));
  55003. //# sourceMappingURL=babylon.gamepadManager.js.map
  55004. var BABYLON;
  55005. (function (BABYLON) {
  55006. var StickValues = /** @class */ (function () {
  55007. function StickValues(x, y) {
  55008. this.x = x;
  55009. this.y = y;
  55010. }
  55011. return StickValues;
  55012. }());
  55013. BABYLON.StickValues = StickValues;
  55014. var Gamepad = /** @class */ (function () {
  55015. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55016. if (leftStickX === void 0) { leftStickX = 0; }
  55017. if (leftStickY === void 0) { leftStickY = 1; }
  55018. if (rightStickX === void 0) { rightStickX = 2; }
  55019. if (rightStickY === void 0) { rightStickY = 3; }
  55020. this.id = id;
  55021. this.index = index;
  55022. this.browserGamepad = browserGamepad;
  55023. this._isConnected = true;
  55024. this.type = Gamepad.GAMEPAD;
  55025. this._leftStickAxisX = leftStickX;
  55026. this._leftStickAxisY = leftStickY;
  55027. this._rightStickAxisX = rightStickX;
  55028. this._rightStickAxisY = rightStickY;
  55029. if (this.browserGamepad.axes.length >= 2) {
  55030. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55031. }
  55032. if (this.browserGamepad.axes.length >= 4) {
  55033. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55034. }
  55035. }
  55036. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55037. get: function () {
  55038. return this._isConnected;
  55039. },
  55040. enumerable: true,
  55041. configurable: true
  55042. });
  55043. Gamepad.prototype.onleftstickchanged = function (callback) {
  55044. this._onleftstickchanged = callback;
  55045. };
  55046. Gamepad.prototype.onrightstickchanged = function (callback) {
  55047. this._onrightstickchanged = callback;
  55048. };
  55049. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55050. get: function () {
  55051. return this._leftStick;
  55052. },
  55053. set: function (newValues) {
  55054. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55055. this._onleftstickchanged(newValues);
  55056. }
  55057. this._leftStick = newValues;
  55058. },
  55059. enumerable: true,
  55060. configurable: true
  55061. });
  55062. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55063. get: function () {
  55064. return this._rightStick;
  55065. },
  55066. set: function (newValues) {
  55067. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55068. this._onrightstickchanged(newValues);
  55069. }
  55070. this._rightStick = newValues;
  55071. },
  55072. enumerable: true,
  55073. configurable: true
  55074. });
  55075. Gamepad.prototype.update = function () {
  55076. if (this._leftStick) {
  55077. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55078. }
  55079. if (this._rightStick) {
  55080. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55081. }
  55082. };
  55083. Gamepad.prototype.dispose = function () {
  55084. };
  55085. Gamepad.GAMEPAD = 0;
  55086. Gamepad.GENERIC = 1;
  55087. Gamepad.XBOX = 2;
  55088. Gamepad.POSE_ENABLED = 3;
  55089. return Gamepad;
  55090. }());
  55091. BABYLON.Gamepad = Gamepad;
  55092. var GenericPad = /** @class */ (function (_super) {
  55093. __extends(GenericPad, _super);
  55094. function GenericPad(id, index, browserGamepad) {
  55095. var _this = _super.call(this, id, index, browserGamepad) || this;
  55096. _this.onButtonDownObservable = new BABYLON.Observable();
  55097. _this.onButtonUpObservable = new BABYLON.Observable();
  55098. _this.type = Gamepad.GENERIC;
  55099. _this._buttons = new Array(browserGamepad.buttons.length);
  55100. return _this;
  55101. }
  55102. GenericPad.prototype.onbuttondown = function (callback) {
  55103. this._onbuttondown = callback;
  55104. };
  55105. GenericPad.prototype.onbuttonup = function (callback) {
  55106. this._onbuttonup = callback;
  55107. };
  55108. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55109. if (newValue !== currentValue) {
  55110. if (newValue === 1) {
  55111. if (this._onbuttondown) {
  55112. this._onbuttondown(buttonIndex);
  55113. }
  55114. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55115. }
  55116. if (newValue === 0) {
  55117. if (this._onbuttonup) {
  55118. this._onbuttonup(buttonIndex);
  55119. }
  55120. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55121. }
  55122. }
  55123. return newValue;
  55124. };
  55125. GenericPad.prototype.update = function () {
  55126. _super.prototype.update.call(this);
  55127. for (var index = 0; index < this._buttons.length; index++) {
  55128. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55129. }
  55130. };
  55131. return GenericPad;
  55132. }(Gamepad));
  55133. BABYLON.GenericPad = GenericPad;
  55134. })(BABYLON || (BABYLON = {}));
  55135. //# sourceMappingURL=babylon.gamepad.js.map
  55136. var BABYLON;
  55137. (function (BABYLON) {
  55138. var Xbox360Button;
  55139. (function (Xbox360Button) {
  55140. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55141. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55142. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55143. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55144. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55145. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55146. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55147. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55148. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55149. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55150. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55151. var Xbox360Dpad;
  55152. (function (Xbox360Dpad) {
  55153. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55154. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55155. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55156. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55157. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55158. var Xbox360Pad = /** @class */ (function (_super) {
  55159. __extends(Xbox360Pad, _super);
  55160. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55161. if (xboxOne === void 0) { xboxOne = false; }
  55162. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55163. _this._leftTrigger = 0;
  55164. _this._rightTrigger = 0;
  55165. _this.onButtonDownObservable = new BABYLON.Observable();
  55166. _this.onButtonUpObservable = new BABYLON.Observable();
  55167. _this.onPadDownObservable = new BABYLON.Observable();
  55168. _this.onPadUpObservable = new BABYLON.Observable();
  55169. _this._buttonA = 0;
  55170. _this._buttonB = 0;
  55171. _this._buttonX = 0;
  55172. _this._buttonY = 0;
  55173. _this._buttonBack = 0;
  55174. _this._buttonStart = 0;
  55175. _this._buttonLB = 0;
  55176. _this._buttonRB = 0;
  55177. _this._buttonLeftStick = 0;
  55178. _this._buttonRightStick = 0;
  55179. _this._dPadUp = 0;
  55180. _this._dPadDown = 0;
  55181. _this._dPadLeft = 0;
  55182. _this._dPadRight = 0;
  55183. _this._isXboxOnePad = false;
  55184. _this.type = BABYLON.Gamepad.XBOX;
  55185. _this._isXboxOnePad = xboxOne;
  55186. return _this;
  55187. }
  55188. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55189. this._onlefttriggerchanged = callback;
  55190. };
  55191. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55192. this._onrighttriggerchanged = callback;
  55193. };
  55194. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55195. get: function () {
  55196. return this._leftTrigger;
  55197. },
  55198. set: function (newValue) {
  55199. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55200. this._onlefttriggerchanged(newValue);
  55201. }
  55202. this._leftTrigger = newValue;
  55203. },
  55204. enumerable: true,
  55205. configurable: true
  55206. });
  55207. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55208. get: function () {
  55209. return this._rightTrigger;
  55210. },
  55211. set: function (newValue) {
  55212. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55213. this._onrighttriggerchanged(newValue);
  55214. }
  55215. this._rightTrigger = newValue;
  55216. },
  55217. enumerable: true,
  55218. configurable: true
  55219. });
  55220. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55221. this._onbuttondown = callback;
  55222. };
  55223. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55224. this._onbuttonup = callback;
  55225. };
  55226. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55227. this._ondpaddown = callback;
  55228. };
  55229. Xbox360Pad.prototype.ondpadup = function (callback) {
  55230. this._ondpadup = callback;
  55231. };
  55232. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55233. if (newValue !== currentValue) {
  55234. if (newValue === 1) {
  55235. if (this._onbuttondown) {
  55236. this._onbuttondown(buttonType);
  55237. }
  55238. this.onButtonDownObservable.notifyObservers(buttonType);
  55239. }
  55240. if (newValue === 0) {
  55241. if (this._onbuttonup) {
  55242. this._onbuttonup(buttonType);
  55243. }
  55244. this.onButtonUpObservable.notifyObservers(buttonType);
  55245. }
  55246. }
  55247. return newValue;
  55248. };
  55249. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55250. if (newValue !== currentValue) {
  55251. if (newValue === 1) {
  55252. if (this._ondpaddown) {
  55253. this._ondpaddown(buttonType);
  55254. }
  55255. this.onPadDownObservable.notifyObservers(buttonType);
  55256. }
  55257. if (newValue === 0) {
  55258. if (this._ondpadup) {
  55259. this._ondpadup(buttonType);
  55260. }
  55261. this.onPadUpObservable.notifyObservers(buttonType);
  55262. }
  55263. }
  55264. return newValue;
  55265. };
  55266. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55267. get: function () {
  55268. return this._buttonA;
  55269. },
  55270. set: function (value) {
  55271. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55272. },
  55273. enumerable: true,
  55274. configurable: true
  55275. });
  55276. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55277. get: function () {
  55278. return this._buttonB;
  55279. },
  55280. set: function (value) {
  55281. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55282. },
  55283. enumerable: true,
  55284. configurable: true
  55285. });
  55286. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55287. get: function () {
  55288. return this._buttonX;
  55289. },
  55290. set: function (value) {
  55291. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55292. },
  55293. enumerable: true,
  55294. configurable: true
  55295. });
  55296. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55297. get: function () {
  55298. return this._buttonY;
  55299. },
  55300. set: function (value) {
  55301. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55302. },
  55303. enumerable: true,
  55304. configurable: true
  55305. });
  55306. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55307. get: function () {
  55308. return this._buttonStart;
  55309. },
  55310. set: function (value) {
  55311. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55312. },
  55313. enumerable: true,
  55314. configurable: true
  55315. });
  55316. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55317. get: function () {
  55318. return this._buttonBack;
  55319. },
  55320. set: function (value) {
  55321. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55322. },
  55323. enumerable: true,
  55324. configurable: true
  55325. });
  55326. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55327. get: function () {
  55328. return this._buttonLB;
  55329. },
  55330. set: function (value) {
  55331. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55332. },
  55333. enumerable: true,
  55334. configurable: true
  55335. });
  55336. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55337. get: function () {
  55338. return this._buttonRB;
  55339. },
  55340. set: function (value) {
  55341. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55342. },
  55343. enumerable: true,
  55344. configurable: true
  55345. });
  55346. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55347. get: function () {
  55348. return this._buttonLeftStick;
  55349. },
  55350. set: function (value) {
  55351. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55352. },
  55353. enumerable: true,
  55354. configurable: true
  55355. });
  55356. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55357. get: function () {
  55358. return this._buttonRightStick;
  55359. },
  55360. set: function (value) {
  55361. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55362. },
  55363. enumerable: true,
  55364. configurable: true
  55365. });
  55366. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55367. get: function () {
  55368. return this._dPadUp;
  55369. },
  55370. set: function (value) {
  55371. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55372. },
  55373. enumerable: true,
  55374. configurable: true
  55375. });
  55376. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55377. get: function () {
  55378. return this._dPadDown;
  55379. },
  55380. set: function (value) {
  55381. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55382. },
  55383. enumerable: true,
  55384. configurable: true
  55385. });
  55386. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55387. get: function () {
  55388. return this._dPadLeft;
  55389. },
  55390. set: function (value) {
  55391. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55392. },
  55393. enumerable: true,
  55394. configurable: true
  55395. });
  55396. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55397. get: function () {
  55398. return this._dPadRight;
  55399. },
  55400. set: function (value) {
  55401. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55402. },
  55403. enumerable: true,
  55404. configurable: true
  55405. });
  55406. Xbox360Pad.prototype.update = function () {
  55407. _super.prototype.update.call(this);
  55408. if (this._isXboxOnePad) {
  55409. this.buttonA = this.browserGamepad.buttons[0].value;
  55410. this.buttonB = this.browserGamepad.buttons[1].value;
  55411. this.buttonX = this.browserGamepad.buttons[2].value;
  55412. this.buttonY = this.browserGamepad.buttons[3].value;
  55413. this.buttonLB = this.browserGamepad.buttons[4].value;
  55414. this.buttonRB = this.browserGamepad.buttons[5].value;
  55415. this.leftTrigger = this.browserGamepad.axes[2];
  55416. this.rightTrigger = this.browserGamepad.axes[5];
  55417. this.buttonBack = this.browserGamepad.buttons[9].value;
  55418. this.buttonStart = this.browserGamepad.buttons[8].value;
  55419. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55420. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55421. this.dPadUp = this.browserGamepad.buttons[11].value;
  55422. this.dPadDown = this.browserGamepad.buttons[12].value;
  55423. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55424. this.dPadRight = this.browserGamepad.buttons[14].value;
  55425. }
  55426. else {
  55427. this.buttonA = this.browserGamepad.buttons[0].value;
  55428. this.buttonB = this.browserGamepad.buttons[1].value;
  55429. this.buttonX = this.browserGamepad.buttons[2].value;
  55430. this.buttonY = this.browserGamepad.buttons[3].value;
  55431. this.buttonLB = this.browserGamepad.buttons[4].value;
  55432. this.buttonRB = this.browserGamepad.buttons[5].value;
  55433. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55434. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55435. this.buttonBack = this.browserGamepad.buttons[8].value;
  55436. this.buttonStart = this.browserGamepad.buttons[9].value;
  55437. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55438. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55439. this.dPadUp = this.browserGamepad.buttons[12].value;
  55440. this.dPadDown = this.browserGamepad.buttons[13].value;
  55441. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55442. this.dPadRight = this.browserGamepad.buttons[15].value;
  55443. }
  55444. };
  55445. return Xbox360Pad;
  55446. }(BABYLON.Gamepad));
  55447. BABYLON.Xbox360Pad = Xbox360Pad;
  55448. })(BABYLON || (BABYLON = {}));
  55449. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55450. var BABYLON;
  55451. (function (BABYLON) {
  55452. var PoseEnabledControllerType;
  55453. (function (PoseEnabledControllerType) {
  55454. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55455. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55456. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55457. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55458. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55459. var PoseEnabledControllerHelper = /** @class */ (function () {
  55460. function PoseEnabledControllerHelper() {
  55461. }
  55462. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55463. // Oculus Touch
  55464. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55465. return new BABYLON.OculusTouchController(vrGamepad);
  55466. }
  55467. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55468. return new BABYLON.WindowsMotionController(vrGamepad);
  55469. }
  55470. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55471. return new BABYLON.ViveController(vrGamepad);
  55472. }
  55473. else {
  55474. return new BABYLON.GenericController(vrGamepad);
  55475. }
  55476. };
  55477. return PoseEnabledControllerHelper;
  55478. }());
  55479. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55480. var PoseEnabledController = /** @class */ (function (_super) {
  55481. __extends(PoseEnabledController, _super);
  55482. function PoseEnabledController(browserGamepad) {
  55483. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55484. _this.deviceScaleFactor = 1;
  55485. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55486. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55487. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55488. _this.position = BABYLON.Vector3.Zero();
  55489. _this.rotationQuaternion = new BABYLON.Quaternion();
  55490. _this.devicePosition = BABYLON.Vector3.Zero();
  55491. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55492. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55493. _this._calculatedRotation = new BABYLON.Quaternion();
  55494. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55495. return _this;
  55496. }
  55497. PoseEnabledController.prototype.update = function () {
  55498. _super.prototype.update.call(this);
  55499. var pose = this.browserGamepad.pose;
  55500. this.updateFromDevice(pose);
  55501. if (this._mesh) {
  55502. this._mesh.position.copyFrom(this._calculatedPosition);
  55503. if (this._mesh.rotationQuaternion) {
  55504. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55505. }
  55506. }
  55507. };
  55508. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55509. if (poseData) {
  55510. this.rawPose = poseData;
  55511. if (poseData.position) {
  55512. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55513. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55514. this.devicePosition.z *= -1;
  55515. }
  55516. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55517. this._calculatedPosition.addInPlace(this.position);
  55518. }
  55519. var pose = this.rawPose;
  55520. if (poseData.orientation && pose.orientation) {
  55521. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55522. if (this._mesh) {
  55523. if (this._mesh.getScene().useRightHandedSystem) {
  55524. this.deviceRotationQuaternion.z *= -1;
  55525. this.deviceRotationQuaternion.w *= -1;
  55526. }
  55527. else {
  55528. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55529. }
  55530. }
  55531. // if the camera is set, rotate to the camera's rotation
  55532. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55533. }
  55534. }
  55535. };
  55536. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55537. if (this._mesh) {
  55538. this._mesh.parent = null;
  55539. }
  55540. this._mesh = mesh;
  55541. if (this._poseControlledCamera) {
  55542. this._mesh.parent = this._poseControlledCamera;
  55543. }
  55544. if (!this._mesh.rotationQuaternion) {
  55545. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55546. }
  55547. };
  55548. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55549. this._poseControlledCamera = camera;
  55550. if (this._mesh) {
  55551. this._mesh.parent = this._poseControlledCamera;
  55552. }
  55553. };
  55554. PoseEnabledController.prototype.dispose = function () {
  55555. if (this._mesh) {
  55556. this._mesh.dispose();
  55557. }
  55558. this._mesh = null;
  55559. _super.prototype.dispose.call(this);
  55560. };
  55561. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55562. get: function () {
  55563. return this._mesh;
  55564. },
  55565. enumerable: true,
  55566. configurable: true
  55567. });
  55568. PoseEnabledController.prototype.getForwardRay = function (length) {
  55569. if (length === void 0) { length = 100; }
  55570. if (!this.mesh) {
  55571. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55572. }
  55573. var m = this.mesh.getWorldMatrix();
  55574. var origin = m.getTranslation();
  55575. var forward = new BABYLON.Vector3(0, 0, -1);
  55576. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55577. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55578. return new BABYLON.Ray(origin, direction, length);
  55579. };
  55580. return PoseEnabledController;
  55581. }(BABYLON.Gamepad));
  55582. BABYLON.PoseEnabledController = PoseEnabledController;
  55583. })(BABYLON || (BABYLON = {}));
  55584. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55585. var BABYLON;
  55586. (function (BABYLON) {
  55587. var WebVRController = /** @class */ (function (_super) {
  55588. __extends(WebVRController, _super);
  55589. function WebVRController(vrGamepad) {
  55590. var _this = _super.call(this, vrGamepad) || this;
  55591. // Observables
  55592. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55593. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55594. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55595. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55596. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55597. _this.pad = { x: 0, y: 0 };
  55598. // avoid GC, store state in a tmp object
  55599. _this._changes = {
  55600. pressChanged: false,
  55601. touchChanged: false,
  55602. valueChanged: false,
  55603. changed: false
  55604. };
  55605. _this._buttons = new Array(vrGamepad.buttons.length);
  55606. _this.hand = vrGamepad.hand;
  55607. return _this;
  55608. }
  55609. WebVRController.prototype.onButtonStateChange = function (callback) {
  55610. this._onButtonStateChange = callback;
  55611. };
  55612. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55613. get: function () {
  55614. return this._defaultModel;
  55615. },
  55616. enumerable: true,
  55617. configurable: true
  55618. });
  55619. WebVRController.prototype.update = function () {
  55620. _super.prototype.update.call(this);
  55621. for (var index = 0; index < this._buttons.length; index++) {
  55622. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55623. }
  55624. ;
  55625. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55626. this.pad.x = this.leftStick.x;
  55627. this.pad.y = this.leftStick.y;
  55628. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55629. }
  55630. };
  55631. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55632. if (!newState) {
  55633. newState = {
  55634. pressed: false,
  55635. touched: false,
  55636. value: 0
  55637. };
  55638. }
  55639. if (!currentState) {
  55640. this._buttons[buttonIndex] = {
  55641. pressed: newState.pressed,
  55642. touched: newState.touched,
  55643. value: newState.value
  55644. };
  55645. return;
  55646. }
  55647. this._checkChanges(newState, currentState);
  55648. if (this._changes.changed) {
  55649. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55650. this.handleButtonChange(buttonIndex, newState, this._changes);
  55651. }
  55652. this._buttons[buttonIndex].pressed = newState.pressed;
  55653. this._buttons[buttonIndex].touched = newState.touched;
  55654. // oculus triggers are never 0, thou not touched.
  55655. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55656. };
  55657. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55658. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55659. this._changes.touchChanged = newState.touched !== currentState.touched;
  55660. this._changes.valueChanged = newState.value !== currentState.value;
  55661. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55662. return this._changes;
  55663. };
  55664. WebVRController.prototype.dispose = function () {
  55665. _super.prototype.dispose.call(this);
  55666. this.onTriggerStateChangedObservable.clear();
  55667. this.onMainButtonStateChangedObservable.clear();
  55668. this.onSecondaryButtonStateChangedObservable.clear();
  55669. this.onPadStateChangedObservable.clear();
  55670. this.onPadValuesChangedObservable.clear();
  55671. };
  55672. return WebVRController;
  55673. }(BABYLON.PoseEnabledController));
  55674. BABYLON.WebVRController = WebVRController;
  55675. })(BABYLON || (BABYLON = {}));
  55676. //# sourceMappingURL=babylon.webVRController.js.map
  55677. var BABYLON;
  55678. (function (BABYLON) {
  55679. var OculusTouchController = /** @class */ (function (_super) {
  55680. __extends(OculusTouchController, _super);
  55681. function OculusTouchController(vrGamepad) {
  55682. var _this = _super.call(this, vrGamepad) || this;
  55683. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55684. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55685. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55686. return _this;
  55687. }
  55688. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55689. var _this = this;
  55690. var meshName;
  55691. // Hand
  55692. if (this.hand === 'left') {
  55693. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55694. }
  55695. else {
  55696. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55697. }
  55698. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55699. /*
  55700. Parent Mesh name: oculus_touch_left
  55701. - body
  55702. - trigger
  55703. - thumbstick
  55704. - grip
  55705. - button_y
  55706. - button_x
  55707. - button_enter
  55708. */
  55709. _this._defaultModel = newMeshes[1];
  55710. _this.attachToMesh(_this._defaultModel);
  55711. if (meshLoaded) {
  55712. meshLoaded(_this._defaultModel);
  55713. }
  55714. });
  55715. };
  55716. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55717. // helper getters for left and right hand.
  55718. get: function () {
  55719. if (this.hand === 'right') {
  55720. return this.onMainButtonStateChangedObservable;
  55721. }
  55722. else {
  55723. throw new Error('No A button on left hand');
  55724. }
  55725. },
  55726. enumerable: true,
  55727. configurable: true
  55728. });
  55729. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55730. get: function () {
  55731. if (this.hand === 'right') {
  55732. return this.onSecondaryButtonStateChangedObservable;
  55733. }
  55734. else {
  55735. throw new Error('No B button on left hand');
  55736. }
  55737. },
  55738. enumerable: true,
  55739. configurable: true
  55740. });
  55741. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55742. get: function () {
  55743. if (this.hand === 'left') {
  55744. return this.onMainButtonStateChangedObservable;
  55745. }
  55746. else {
  55747. throw new Error('No X button on right hand');
  55748. }
  55749. },
  55750. enumerable: true,
  55751. configurable: true
  55752. });
  55753. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55754. get: function () {
  55755. if (this.hand === 'left') {
  55756. return this.onSecondaryButtonStateChangedObservable;
  55757. }
  55758. else {
  55759. throw new Error('No Y button on right hand');
  55760. }
  55761. },
  55762. enumerable: true,
  55763. configurable: true
  55764. });
  55765. /*
  55766. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55767. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55768. 2) secondary trigger (same)
  55769. 3) A (right) X (left), touch, pressed = value
  55770. 4) B / Y
  55771. 5) thumb rest
  55772. */
  55773. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55774. var notifyObject = state; //{ state: state, changes: changes };
  55775. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55776. switch (buttonIdx) {
  55777. case 0:
  55778. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55779. return;
  55780. case 1:// index trigger
  55781. if (this._defaultModel) {
  55782. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55783. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55784. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55785. }
  55786. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55787. return;
  55788. case 2:// secondary trigger
  55789. if (this._defaultModel) {
  55790. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55791. }
  55792. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55793. return;
  55794. case 3:
  55795. if (this._defaultModel) {
  55796. if (notifyObject.pressed) {
  55797. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55798. }
  55799. else {
  55800. (this._defaultModel.getChildren()[1]).position.y = 0;
  55801. }
  55802. }
  55803. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55804. return;
  55805. case 4:
  55806. if (this._defaultModel) {
  55807. if (notifyObject.pressed) {
  55808. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55809. }
  55810. else {
  55811. (this._defaultModel.getChildren()[2]).position.y = 0;
  55812. }
  55813. }
  55814. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55815. return;
  55816. case 5:
  55817. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55818. return;
  55819. }
  55820. };
  55821. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55822. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55823. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55824. return OculusTouchController;
  55825. }(BABYLON.WebVRController));
  55826. BABYLON.OculusTouchController = OculusTouchController;
  55827. })(BABYLON || (BABYLON = {}));
  55828. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55829. var BABYLON;
  55830. (function (BABYLON) {
  55831. var ViveController = /** @class */ (function (_super) {
  55832. __extends(ViveController, _super);
  55833. function ViveController(vrGamepad) {
  55834. var _this = _super.call(this, vrGamepad) || this;
  55835. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55836. return _this;
  55837. }
  55838. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55839. var _this = this;
  55840. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55841. /*
  55842. Parent Mesh name: ViveWand
  55843. - body
  55844. - r_gripper
  55845. - l_gripper
  55846. - menu_button
  55847. - system_button
  55848. - trackpad
  55849. - trigger
  55850. - LED
  55851. */
  55852. _this._defaultModel = newMeshes[1];
  55853. _this.attachToMesh(_this._defaultModel);
  55854. if (meshLoaded) {
  55855. meshLoaded(_this._defaultModel);
  55856. }
  55857. });
  55858. };
  55859. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55860. get: function () {
  55861. return this.onMainButtonStateChangedObservable;
  55862. },
  55863. enumerable: true,
  55864. configurable: true
  55865. });
  55866. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55867. get: function () {
  55868. return this.onMainButtonStateChangedObservable;
  55869. },
  55870. enumerable: true,
  55871. configurable: true
  55872. });
  55873. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55874. get: function () {
  55875. return this.onSecondaryButtonStateChangedObservable;
  55876. },
  55877. enumerable: true,
  55878. configurable: true
  55879. });
  55880. /**
  55881. * Vive mapping:
  55882. * 0: touchpad
  55883. * 1: trigger
  55884. * 2: left AND right buttons
  55885. * 3: menu button
  55886. */
  55887. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55888. var notifyObject = state; //{ state: state, changes: changes };
  55889. switch (buttonIdx) {
  55890. case 0:
  55891. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55892. return;
  55893. case 1:// index trigger
  55894. if (this._defaultModel) {
  55895. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55896. }
  55897. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55898. return;
  55899. case 2:// left AND right button
  55900. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55901. return;
  55902. case 3:
  55903. if (this._defaultModel) {
  55904. if (notifyObject.pressed) {
  55905. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55906. }
  55907. else {
  55908. (this._defaultModel.getChildren()[2]).position.y = 0;
  55909. }
  55910. }
  55911. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55912. return;
  55913. }
  55914. };
  55915. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55916. ViveController.MODEL_FILENAME = 'wand.babylon';
  55917. return ViveController;
  55918. }(BABYLON.WebVRController));
  55919. BABYLON.ViveController = ViveController;
  55920. })(BABYLON || (BABYLON = {}));
  55921. //# sourceMappingURL=babylon.viveController.js.map
  55922. var BABYLON;
  55923. (function (BABYLON) {
  55924. var GenericController = /** @class */ (function (_super) {
  55925. __extends(GenericController, _super);
  55926. function GenericController(vrGamepad) {
  55927. return _super.call(this, vrGamepad) || this;
  55928. }
  55929. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55930. var _this = this;
  55931. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55932. _this._defaultModel = newMeshes[1];
  55933. _this.attachToMesh(_this._defaultModel);
  55934. if (meshLoaded) {
  55935. meshLoaded(_this._defaultModel);
  55936. }
  55937. });
  55938. };
  55939. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55940. console.log("Button id: " + buttonIdx + "state: ");
  55941. console.dir(state);
  55942. };
  55943. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55944. GenericController.MODEL_FILENAME = 'generic.babylon';
  55945. return GenericController;
  55946. }(BABYLON.WebVRController));
  55947. BABYLON.GenericController = GenericController;
  55948. })(BABYLON || (BABYLON = {}));
  55949. //# sourceMappingURL=babylon.genericController.js.map
  55950. var BABYLON;
  55951. (function (BABYLON) {
  55952. var LoadedMeshInfo = /** @class */ (function () {
  55953. function LoadedMeshInfo() {
  55954. this.buttonMeshes = {};
  55955. this.axisMeshes = {};
  55956. }
  55957. return LoadedMeshInfo;
  55958. }());
  55959. var WindowsMotionController = /** @class */ (function (_super) {
  55960. __extends(WindowsMotionController, _super);
  55961. function WindowsMotionController(vrGamepad) {
  55962. var _this = _super.call(this, vrGamepad) || this;
  55963. _this._mapping = {
  55964. // Semantic button names
  55965. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55966. // A mapping of the button name to glTF model node name
  55967. // that should be transformed by button value.
  55968. buttonMeshNames: {
  55969. 'trigger': 'SELECT',
  55970. 'menu': 'MENU',
  55971. 'grip': 'GRASP',
  55972. 'thumbstick': 'THUMBSTICK_PRESS',
  55973. 'trackpad': 'TOUCHPAD_PRESS'
  55974. },
  55975. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55976. buttonObservableNames: {
  55977. 'trigger': 'onTriggerStateChangedObservable',
  55978. 'menu': 'onSecondaryButtonStateChangedObservable',
  55979. 'grip': 'onMainButtonStateChangedObservable',
  55980. 'thumbstick': 'onPadStateChangedObservable',
  55981. 'trackpad': 'onTrackpadChangedObservable'
  55982. },
  55983. // A mapping of the axis name to glTF model node name
  55984. // that should be transformed by axis value.
  55985. // This array mirrors the browserGamepad.axes array, such that
  55986. // the mesh corresponding to axis 0 is in this array index 0.
  55987. axisMeshNames: [
  55988. 'THUMBSTICK_X',
  55989. 'THUMBSTICK_Y',
  55990. 'TOUCHPAD_TOUCH_X',
  55991. 'TOUCHPAD_TOUCH_Y'
  55992. ],
  55993. pointingPoseMeshName: 'POINTING_POSE'
  55994. };
  55995. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55996. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55997. _this._loadedMeshInfo = null;
  55998. return _this;
  55999. }
  56000. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56001. get: function () {
  56002. return this.onTriggerStateChangedObservable;
  56003. },
  56004. enumerable: true,
  56005. configurable: true
  56006. });
  56007. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56008. get: function () {
  56009. return this.onSecondaryButtonStateChangedObservable;
  56010. },
  56011. enumerable: true,
  56012. configurable: true
  56013. });
  56014. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56015. get: function () {
  56016. return this.onMainButtonStateChangedObservable;
  56017. },
  56018. enumerable: true,
  56019. configurable: true
  56020. });
  56021. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56022. get: function () {
  56023. return this.onPadStateChangedObservable;
  56024. },
  56025. enumerable: true,
  56026. configurable: true
  56027. });
  56028. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56029. get: function () {
  56030. return this.onTrackpadChangedObservable;
  56031. },
  56032. enumerable: true,
  56033. configurable: true
  56034. });
  56035. /**
  56036. * Called once per frame by the engine.
  56037. */
  56038. WindowsMotionController.prototype.update = function () {
  56039. _super.prototype.update.call(this);
  56040. // Only need to animate axes if there is a loaded mesh
  56041. if (this._loadedMeshInfo) {
  56042. if (this.browserGamepad.axes) {
  56043. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56044. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56045. }
  56046. }
  56047. }
  56048. };
  56049. /**
  56050. * Called once for each button that changed state since the last frame
  56051. * @param buttonIdx Which button index changed
  56052. * @param state New state of the button
  56053. * @param changes Which properties on the state changed since last frame
  56054. */
  56055. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56056. var buttonName = this._mapping.buttons[buttonIdx];
  56057. if (!buttonName) {
  56058. return;
  56059. }
  56060. // Only emit events for buttons that we know how to map from index to name
  56061. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56062. if (observable) {
  56063. observable.notifyObservers(state);
  56064. }
  56065. this.lerpButtonTransform(buttonName, state.value);
  56066. };
  56067. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56068. // If there is no loaded mesh, there is nothing to transform.
  56069. if (!this._loadedMeshInfo) {
  56070. return;
  56071. }
  56072. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56073. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56074. return;
  56075. }
  56076. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56077. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56078. };
  56079. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56080. if (!this._loadedMeshInfo) {
  56081. return;
  56082. }
  56083. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56084. if (!meshInfo) {
  56085. return;
  56086. }
  56087. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56088. return;
  56089. }
  56090. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56091. var lerpValue = axisValue * 0.5 + 0.5;
  56092. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56093. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56094. };
  56095. /**
  56096. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56097. * @param scene scene in which to add meshes
  56098. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56099. */
  56100. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56101. var _this = this;
  56102. if (forceDefault === void 0) { forceDefault = false; }
  56103. var path;
  56104. var filename;
  56105. // Checking if GLB loader is present
  56106. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56107. // Determine the device specific folder based on the ID suffix
  56108. var device = 'default';
  56109. if (this.id && !forceDefault) {
  56110. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56111. device = ((match && match[0]) || device);
  56112. }
  56113. // Hand
  56114. if (this.hand === 'left') {
  56115. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56116. }
  56117. else {
  56118. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56119. }
  56120. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56121. }
  56122. else {
  56123. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56124. path = BABYLON.GenericController.MODEL_BASE_URL;
  56125. filename = BABYLON.GenericController.MODEL_FILENAME;
  56126. }
  56127. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56128. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56129. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56130. if (!_this._loadedMeshInfo) {
  56131. return;
  56132. }
  56133. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56134. _this.attachToMesh(_this._defaultModel);
  56135. if (meshLoaded) {
  56136. meshLoaded(_this._defaultModel);
  56137. }
  56138. }, null, function (scene, message) {
  56139. BABYLON.Tools.Log(message);
  56140. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56141. if (!forceDefault) {
  56142. _this.initControllerMesh(scene, meshLoaded, true);
  56143. }
  56144. });
  56145. };
  56146. /**
  56147. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56148. * can be transformed by button presses and axes values, based on this._mapping.
  56149. *
  56150. * @param scene scene in which the meshes exist
  56151. * @param meshes list of meshes that make up the controller model to process
  56152. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56153. */
  56154. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56155. var loadedMeshInfo = null;
  56156. // Create a new mesh to contain the glTF hierarchy
  56157. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56158. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56159. var childMesh = null;
  56160. for (var i = 0; i < meshes.length; i++) {
  56161. var mesh = meshes[i];
  56162. if (!mesh.parent) {
  56163. // Exclude controller meshes from picking results
  56164. mesh.isPickable = false;
  56165. // Handle root node, attach to the new parentMesh
  56166. childMesh = mesh;
  56167. break;
  56168. }
  56169. }
  56170. if (childMesh) {
  56171. childMesh.setParent(parentMesh);
  56172. // Create our mesh info. Note that this method will always return non-null.
  56173. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56174. }
  56175. else {
  56176. BABYLON.Tools.Warn('Could not find root node in model file.');
  56177. }
  56178. return loadedMeshInfo;
  56179. };
  56180. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56181. var loadedMeshInfo = new LoadedMeshInfo();
  56182. var i;
  56183. loadedMeshInfo.rootNode = rootNode;
  56184. // Reset the caches
  56185. loadedMeshInfo.buttonMeshes = {};
  56186. loadedMeshInfo.axisMeshes = {};
  56187. // Button Meshes
  56188. for (i = 0; i < this._mapping.buttons.length; i++) {
  56189. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56190. if (!buttonMeshName) {
  56191. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56192. continue;
  56193. }
  56194. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56195. if (!buttonMesh) {
  56196. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56197. continue;
  56198. }
  56199. var buttonMeshInfo = {
  56200. index: i,
  56201. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56202. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56203. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56204. };
  56205. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56206. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56207. }
  56208. else {
  56209. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56210. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56211. '(VALUE: ' + !!buttonMeshInfo.value +
  56212. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56213. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56214. ')');
  56215. }
  56216. }
  56217. // Axis Meshes
  56218. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56219. var axisMeshName = this._mapping.axisMeshNames[i];
  56220. if (!axisMeshName) {
  56221. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56222. continue;
  56223. }
  56224. var axisMesh = getChildByName(rootNode, axisMeshName);
  56225. if (!axisMesh) {
  56226. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56227. continue;
  56228. }
  56229. var axisMeshInfo = {
  56230. index: i,
  56231. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56232. min: getImmediateChildByName(axisMesh, 'MIN'),
  56233. max: getImmediateChildByName(axisMesh, 'MAX')
  56234. };
  56235. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56236. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56237. }
  56238. else {
  56239. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56240. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56241. '(VALUE: ' + !!axisMeshInfo.value +
  56242. ', MIN: ' + !!axisMeshInfo.min +
  56243. ', MAX:' + !!axisMeshInfo.max +
  56244. ')');
  56245. }
  56246. }
  56247. // Pointing Ray
  56248. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56249. if (!loadedMeshInfo.pointingPoseNode) {
  56250. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56251. }
  56252. return loadedMeshInfo;
  56253. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56254. function getChildByName(node, name) {
  56255. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56256. }
  56257. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56258. function getImmediateChildByName(node, name) {
  56259. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56260. }
  56261. };
  56262. WindowsMotionController.prototype.getForwardRay = function (length) {
  56263. if (length === void 0) { length = 100; }
  56264. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56265. return _super.prototype.getForwardRay.call(this, length);
  56266. }
  56267. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56268. var origin = m.getTranslation();
  56269. var forward = new BABYLON.Vector3(0, 0, -1);
  56270. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56271. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56272. return new BABYLON.Ray(origin, direction, length);
  56273. };
  56274. WindowsMotionController.prototype.dispose = function () {
  56275. _super.prototype.dispose.call(this);
  56276. this.onTrackpadChangedObservable.clear();
  56277. };
  56278. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56279. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56280. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56281. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56282. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56283. return WindowsMotionController;
  56284. }(BABYLON.WebVRController));
  56285. BABYLON.WindowsMotionController = WindowsMotionController;
  56286. })(BABYLON || (BABYLON = {}));
  56287. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56288. var BABYLON;
  56289. (function (BABYLON) {
  56290. var FollowCamera = /** @class */ (function (_super) {
  56291. __extends(FollowCamera, _super);
  56292. function FollowCamera(name, position, scene, lockedTarget) {
  56293. if (lockedTarget === void 0) { lockedTarget = null; }
  56294. var _this = _super.call(this, name, position, scene) || this;
  56295. _this.radius = 12;
  56296. _this.rotationOffset = 0;
  56297. _this.heightOffset = 4;
  56298. _this.cameraAcceleration = 0.05;
  56299. _this.maxCameraSpeed = 20;
  56300. _this.lockedTarget = lockedTarget;
  56301. return _this;
  56302. }
  56303. FollowCamera.prototype.getRadians = function (degrees) {
  56304. return degrees * Math.PI / 180;
  56305. };
  56306. FollowCamera.prototype.follow = function (cameraTarget) {
  56307. if (!cameraTarget)
  56308. return;
  56309. var yRotation;
  56310. if (cameraTarget.rotationQuaternion) {
  56311. var rotMatrix = new BABYLON.Matrix();
  56312. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56313. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56314. }
  56315. else {
  56316. yRotation = cameraTarget.rotation.y;
  56317. }
  56318. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56319. var targetPosition = cameraTarget.getAbsolutePosition();
  56320. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56321. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56322. var dx = targetX - this.position.x;
  56323. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56324. var dz = (targetZ) - this.position.z;
  56325. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56326. var vy = dy * this.cameraAcceleration;
  56327. var vz = dz * this.cameraAcceleration * 2;
  56328. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56329. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56330. }
  56331. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56332. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56333. }
  56334. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56335. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56336. }
  56337. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56338. this.setTarget(targetPosition);
  56339. };
  56340. FollowCamera.prototype._checkInputs = function () {
  56341. _super.prototype._checkInputs.call(this);
  56342. if (this.lockedTarget) {
  56343. this.follow(this.lockedTarget);
  56344. }
  56345. };
  56346. FollowCamera.prototype.getClassName = function () {
  56347. return "FollowCamera";
  56348. };
  56349. __decorate([
  56350. BABYLON.serialize()
  56351. ], FollowCamera.prototype, "radius", void 0);
  56352. __decorate([
  56353. BABYLON.serialize()
  56354. ], FollowCamera.prototype, "rotationOffset", void 0);
  56355. __decorate([
  56356. BABYLON.serialize()
  56357. ], FollowCamera.prototype, "heightOffset", void 0);
  56358. __decorate([
  56359. BABYLON.serialize()
  56360. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56361. __decorate([
  56362. BABYLON.serialize()
  56363. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56364. __decorate([
  56365. BABYLON.serializeAsMeshReference("lockedTargetId")
  56366. ], FollowCamera.prototype, "lockedTarget", void 0);
  56367. return FollowCamera;
  56368. }(BABYLON.TargetCamera));
  56369. BABYLON.FollowCamera = FollowCamera;
  56370. var ArcFollowCamera = /** @class */ (function (_super) {
  56371. __extends(ArcFollowCamera, _super);
  56372. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56373. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56374. _this.alpha = alpha;
  56375. _this.beta = beta;
  56376. _this.radius = radius;
  56377. _this.target = target;
  56378. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56379. _this.follow();
  56380. return _this;
  56381. }
  56382. ArcFollowCamera.prototype.follow = function () {
  56383. if (!this.target) {
  56384. return;
  56385. }
  56386. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56387. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56388. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56389. var targetPosition = this.target.getAbsolutePosition();
  56390. this.position = targetPosition.add(this._cartesianCoordinates);
  56391. this.setTarget(targetPosition);
  56392. };
  56393. ArcFollowCamera.prototype._checkInputs = function () {
  56394. _super.prototype._checkInputs.call(this);
  56395. this.follow();
  56396. };
  56397. ArcFollowCamera.prototype.getClassName = function () {
  56398. return "ArcFollowCamera";
  56399. };
  56400. return ArcFollowCamera;
  56401. }(BABYLON.TargetCamera));
  56402. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56403. })(BABYLON || (BABYLON = {}));
  56404. //# sourceMappingURL=babylon.followCamera.js.map
  56405. var BABYLON;
  56406. (function (BABYLON) {
  56407. // We're mainly based on the logic defined into the FreeCamera code
  56408. var UniversalCamera = /** @class */ (function (_super) {
  56409. __extends(UniversalCamera, _super);
  56410. //-- end properties for backward compatibility for inputs
  56411. function UniversalCamera(name, position, scene) {
  56412. var _this = _super.call(this, name, position, scene) || this;
  56413. _this.inputs.addGamepad();
  56414. return _this;
  56415. }
  56416. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56417. //-- Begin properties for backward compatibility for inputs
  56418. get: function () {
  56419. var gamepad = this.inputs.attached["gamepad"];
  56420. if (gamepad)
  56421. return gamepad.gamepadAngularSensibility;
  56422. return 0;
  56423. },
  56424. set: function (value) {
  56425. var gamepad = this.inputs.attached["gamepad"];
  56426. if (gamepad)
  56427. gamepad.gamepadAngularSensibility = value;
  56428. },
  56429. enumerable: true,
  56430. configurable: true
  56431. });
  56432. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56433. get: function () {
  56434. var gamepad = this.inputs.attached["gamepad"];
  56435. if (gamepad)
  56436. return gamepad.gamepadMoveSensibility;
  56437. return 0;
  56438. },
  56439. set: function (value) {
  56440. var gamepad = this.inputs.attached["gamepad"];
  56441. if (gamepad)
  56442. gamepad.gamepadMoveSensibility = value;
  56443. },
  56444. enumerable: true,
  56445. configurable: true
  56446. });
  56447. UniversalCamera.prototype.getClassName = function () {
  56448. return "UniversalCamera";
  56449. };
  56450. return UniversalCamera;
  56451. }(BABYLON.TouchCamera));
  56452. BABYLON.UniversalCamera = UniversalCamera;
  56453. })(BABYLON || (BABYLON = {}));
  56454. //# sourceMappingURL=babylon.universalCamera.js.map
  56455. var BABYLON;
  56456. (function (BABYLON) {
  56457. // We're mainly based on the logic defined into the FreeCamera code
  56458. var GamepadCamera = /** @class */ (function (_super) {
  56459. __extends(GamepadCamera, _super);
  56460. //-- end properties for backward compatibility for inputs
  56461. function GamepadCamera(name, position, scene) {
  56462. return _super.call(this, name, position, scene) || this;
  56463. }
  56464. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56465. //-- Begin properties for backward compatibility for inputs
  56466. get: function () {
  56467. var gamepad = this.inputs.attached["gamepad"];
  56468. if (gamepad)
  56469. return gamepad.gamepadAngularSensibility;
  56470. return 0;
  56471. },
  56472. set: function (value) {
  56473. var gamepad = this.inputs.attached["gamepad"];
  56474. if (gamepad)
  56475. gamepad.gamepadAngularSensibility = value;
  56476. },
  56477. enumerable: true,
  56478. configurable: true
  56479. });
  56480. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56481. get: function () {
  56482. var gamepad = this.inputs.attached["gamepad"];
  56483. if (gamepad)
  56484. return gamepad.gamepadMoveSensibility;
  56485. return 0;
  56486. },
  56487. set: function (value) {
  56488. var gamepad = this.inputs.attached["gamepad"];
  56489. if (gamepad)
  56490. gamepad.gamepadMoveSensibility = value;
  56491. },
  56492. enumerable: true,
  56493. configurable: true
  56494. });
  56495. GamepadCamera.prototype.getClassName = function () {
  56496. return "GamepadCamera";
  56497. };
  56498. return GamepadCamera;
  56499. }(BABYLON.UniversalCamera));
  56500. BABYLON.GamepadCamera = GamepadCamera;
  56501. })(BABYLON || (BABYLON = {}));
  56502. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56503. var BABYLON;
  56504. (function (BABYLON) {
  56505. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56506. function PostProcessRenderPipelineManager() {
  56507. this._renderPipelines = {};
  56508. }
  56509. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56510. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56511. };
  56512. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56513. if (unique === void 0) { unique = false; }
  56514. var renderPipeline = this._renderPipelines[renderPipelineName];
  56515. if (!renderPipeline) {
  56516. return;
  56517. }
  56518. renderPipeline._attachCameras(cameras, unique);
  56519. };
  56520. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56521. var renderPipeline = this._renderPipelines[renderPipelineName];
  56522. if (!renderPipeline) {
  56523. return;
  56524. }
  56525. renderPipeline._detachCameras(cameras);
  56526. };
  56527. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56528. var renderPipeline = this._renderPipelines[renderPipelineName];
  56529. if (!renderPipeline) {
  56530. return;
  56531. }
  56532. renderPipeline._enableEffect(renderEffectName, cameras);
  56533. };
  56534. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56535. var renderPipeline = this._renderPipelines[renderPipelineName];
  56536. if (!renderPipeline) {
  56537. return;
  56538. }
  56539. renderPipeline._disableEffect(renderEffectName, cameras);
  56540. };
  56541. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56542. var renderPipeline = this._renderPipelines[renderPipelineName];
  56543. if (!renderPipeline) {
  56544. return;
  56545. }
  56546. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56547. };
  56548. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56549. var renderPipeline = this._renderPipelines[renderPipelineName];
  56550. if (!renderPipeline) {
  56551. return;
  56552. }
  56553. renderPipeline._disableDisplayOnlyPass(cameras);
  56554. };
  56555. PostProcessRenderPipelineManager.prototype.update = function () {
  56556. for (var renderPipelineName in this._renderPipelines) {
  56557. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56558. var pipeline = this._renderPipelines[renderPipelineName];
  56559. if (!pipeline.isSupported) {
  56560. pipeline.dispose();
  56561. delete this._renderPipelines[renderPipelineName];
  56562. }
  56563. else {
  56564. pipeline._update();
  56565. }
  56566. }
  56567. }
  56568. };
  56569. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56570. for (var renderPipelineName in this._renderPipelines) {
  56571. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56572. var pipeline = this._renderPipelines[renderPipelineName];
  56573. pipeline._rebuild();
  56574. }
  56575. }
  56576. };
  56577. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56578. for (var renderPipelineName in this._renderPipelines) {
  56579. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56580. var pipeline = this._renderPipelines[renderPipelineName];
  56581. pipeline.dispose();
  56582. }
  56583. }
  56584. };
  56585. return PostProcessRenderPipelineManager;
  56586. }());
  56587. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56588. })(BABYLON || (BABYLON = {}));
  56589. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56590. var BABYLON;
  56591. (function (BABYLON) {
  56592. var PostProcessRenderPass = /** @class */ (function () {
  56593. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56594. this._refCount = 0;
  56595. this._name = name;
  56596. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56597. this.setRenderList(renderList);
  56598. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56599. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56600. this._scene = scene;
  56601. this._renderList = renderList;
  56602. }
  56603. // private
  56604. PostProcessRenderPass.prototype._incRefCount = function () {
  56605. if (this._refCount === 0) {
  56606. this._scene.customRenderTargets.push(this._renderTexture);
  56607. }
  56608. return ++this._refCount;
  56609. };
  56610. PostProcessRenderPass.prototype._decRefCount = function () {
  56611. this._refCount--;
  56612. if (this._refCount <= 0) {
  56613. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56614. }
  56615. return this._refCount;
  56616. };
  56617. PostProcessRenderPass.prototype._update = function () {
  56618. this.setRenderList(this._renderList);
  56619. };
  56620. // public
  56621. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56622. this._renderTexture.renderList = renderList;
  56623. };
  56624. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56625. return this._renderTexture;
  56626. };
  56627. return PostProcessRenderPass;
  56628. }());
  56629. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56630. })(BABYLON || (BABYLON = {}));
  56631. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56632. var BABYLON;
  56633. (function (BABYLON) {
  56634. var PostProcessRenderEffect = /** @class */ (function () {
  56635. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56636. this._engine = engine;
  56637. this._name = name;
  56638. this._singleInstance = singleInstance || true;
  56639. this._getPostProcess = getPostProcess;
  56640. this._cameras = {};
  56641. this._indicesForCamera = {};
  56642. this._postProcesses = {};
  56643. this._renderPasses = {};
  56644. this._renderEffectAsPasses = {};
  56645. }
  56646. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56647. get: function () {
  56648. for (var index in this._postProcesses) {
  56649. if (!this._postProcesses[index].isSupported) {
  56650. return false;
  56651. }
  56652. }
  56653. return true;
  56654. },
  56655. enumerable: true,
  56656. configurable: true
  56657. });
  56658. PostProcessRenderEffect.prototype._update = function () {
  56659. for (var renderPassName in this._renderPasses) {
  56660. this._renderPasses[renderPassName]._update();
  56661. }
  56662. };
  56663. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56664. this._renderPasses[renderPass._name] = renderPass;
  56665. this._linkParameters();
  56666. };
  56667. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56668. delete this._renderPasses[renderPass._name];
  56669. this._linkParameters();
  56670. };
  56671. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56672. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56673. this._linkParameters();
  56674. };
  56675. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56676. for (var renderPassName in this._renderPasses) {
  56677. if (renderPassName === passName) {
  56678. return this._renderPasses[passName];
  56679. }
  56680. }
  56681. return null;
  56682. };
  56683. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56684. this._renderPasses = {};
  56685. this._linkParameters();
  56686. };
  56687. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56688. var cameraKey;
  56689. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56690. if (!cams) {
  56691. return;
  56692. }
  56693. for (var i = 0; i < cams.length; i++) {
  56694. var camera = cams[i];
  56695. var cameraName = camera.name;
  56696. if (this._singleInstance) {
  56697. cameraKey = 0;
  56698. }
  56699. else {
  56700. cameraKey = cameraName;
  56701. }
  56702. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56703. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56704. if (!this._indicesForCamera[cameraName]) {
  56705. this._indicesForCamera[cameraName] = [];
  56706. }
  56707. this._indicesForCamera[cameraName].push(index);
  56708. if (!this._cameras[cameraName]) {
  56709. this._cameras[cameraName] = camera;
  56710. }
  56711. for (var passName in this._renderPasses) {
  56712. this._renderPasses[passName]._incRefCount();
  56713. }
  56714. }
  56715. this._linkParameters();
  56716. };
  56717. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56718. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56719. if (!cams) {
  56720. return;
  56721. }
  56722. for (var i = 0; i < cams.length; i++) {
  56723. var camera = cams[i];
  56724. var cameraName = camera.name;
  56725. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56726. if (this._cameras[cameraName]) {
  56727. //this._indicesForCamera.splice(index, 1);
  56728. this._cameras[cameraName] = null;
  56729. }
  56730. for (var passName in this._renderPasses) {
  56731. this._renderPasses[passName]._decRefCount();
  56732. }
  56733. }
  56734. };
  56735. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56736. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56737. if (!cams) {
  56738. return;
  56739. }
  56740. for (var i = 0; i < cams.length; i++) {
  56741. var camera = cams[i];
  56742. var cameraName = camera.name;
  56743. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56744. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56745. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56746. }
  56747. }
  56748. for (var passName in this._renderPasses) {
  56749. this._renderPasses[passName]._incRefCount();
  56750. }
  56751. }
  56752. };
  56753. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56754. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56755. if (!cams) {
  56756. return;
  56757. }
  56758. for (var i = 0; i < cams.length; i++) {
  56759. var camera = cams[i];
  56760. var cameraName = camera.Name;
  56761. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56762. for (var passName in this._renderPasses) {
  56763. this._renderPasses[passName]._decRefCount();
  56764. }
  56765. }
  56766. };
  56767. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56768. if (this._singleInstance) {
  56769. return this._postProcesses[0];
  56770. }
  56771. else {
  56772. if (!camera) {
  56773. return null;
  56774. }
  56775. return this._postProcesses[camera.name];
  56776. }
  56777. };
  56778. PostProcessRenderEffect.prototype._linkParameters = function () {
  56779. var _this = this;
  56780. for (var index in this._postProcesses) {
  56781. if (this.applyParameters) {
  56782. this.applyParameters(this._postProcesses[index]);
  56783. }
  56784. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56785. _this._linkTextures(effect);
  56786. });
  56787. }
  56788. };
  56789. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56790. for (var renderPassName in this._renderPasses) {
  56791. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56792. }
  56793. for (var renderEffectName in this._renderEffectAsPasses) {
  56794. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56795. }
  56796. };
  56797. return PostProcessRenderEffect;
  56798. }());
  56799. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56800. })(BABYLON || (BABYLON = {}));
  56801. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56802. var BABYLON;
  56803. (function (BABYLON) {
  56804. var PostProcessRenderPipeline = /** @class */ (function () {
  56805. function PostProcessRenderPipeline(engine, name) {
  56806. this._engine = engine;
  56807. this._name = name;
  56808. this._renderEffects = {};
  56809. this._renderEffectsForIsolatedPass = new Array();
  56810. this._cameras = [];
  56811. }
  56812. PostProcessRenderPipeline.prototype.getClassName = function () {
  56813. return "PostProcessRenderPipeline";
  56814. };
  56815. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56816. get: function () {
  56817. for (var renderEffectName in this._renderEffects) {
  56818. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56819. if (!this._renderEffects[renderEffectName].isSupported) {
  56820. return false;
  56821. }
  56822. }
  56823. }
  56824. return true;
  56825. },
  56826. enumerable: true,
  56827. configurable: true
  56828. });
  56829. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56830. this._renderEffects[renderEffect._name] = renderEffect;
  56831. };
  56832. // private
  56833. PostProcessRenderPipeline.prototype._rebuild = function () {
  56834. };
  56835. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56836. var renderEffects = this._renderEffects[renderEffectName];
  56837. if (!renderEffects) {
  56838. return;
  56839. }
  56840. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56841. };
  56842. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56843. var renderEffects = this._renderEffects[renderEffectName];
  56844. if (!renderEffects) {
  56845. return;
  56846. }
  56847. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56848. };
  56849. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56850. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56851. if (!cams) {
  56852. return;
  56853. }
  56854. var indicesToDelete = [];
  56855. var i;
  56856. for (i = 0; i < cams.length; i++) {
  56857. var camera = cams[i];
  56858. var cameraName = camera.name;
  56859. if (this._cameras.indexOf(camera) === -1) {
  56860. this._cameras[cameraName] = camera;
  56861. }
  56862. else if (unique) {
  56863. indicesToDelete.push(i);
  56864. }
  56865. }
  56866. for (i = 0; i < indicesToDelete.length; i++) {
  56867. cameras.splice(indicesToDelete[i], 1);
  56868. }
  56869. for (var renderEffectName in this._renderEffects) {
  56870. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56871. this._renderEffects[renderEffectName]._attachCameras(cams);
  56872. }
  56873. }
  56874. };
  56875. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56876. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56877. if (!cams) {
  56878. return;
  56879. }
  56880. for (var renderEffectName in this._renderEffects) {
  56881. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56882. this._renderEffects[renderEffectName]._detachCameras(cams);
  56883. }
  56884. }
  56885. for (var i = 0; i < cams.length; i++) {
  56886. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56887. }
  56888. };
  56889. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56890. var _this = this;
  56891. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56892. if (!cams) {
  56893. return;
  56894. }
  56895. var pass = null;
  56896. var renderEffectName;
  56897. for (renderEffectName in this._renderEffects) {
  56898. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56899. pass = this._renderEffects[renderEffectName].getPass(passName);
  56900. if (pass != null) {
  56901. break;
  56902. }
  56903. }
  56904. }
  56905. if (pass === null) {
  56906. return;
  56907. }
  56908. for (renderEffectName in this._renderEffects) {
  56909. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56910. this._renderEffects[renderEffectName]._disable(cams);
  56911. }
  56912. }
  56913. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56914. for (var i = 0; i < cams.length; i++) {
  56915. var camera = cams[i];
  56916. var cameraName = camera.name;
  56917. 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); });
  56918. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56919. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56920. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56921. }
  56922. };
  56923. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56924. var _this = this;
  56925. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56926. if (!cams) {
  56927. return;
  56928. }
  56929. for (var i = 0; i < cams.length; i++) {
  56930. var camera = cams[i];
  56931. var cameraName = camera.name;
  56932. 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); });
  56933. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56934. }
  56935. for (var renderEffectName in this._renderEffects) {
  56936. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56937. this._renderEffects[renderEffectName]._enable(cams);
  56938. }
  56939. }
  56940. };
  56941. PostProcessRenderPipeline.prototype._update = function () {
  56942. for (var renderEffectName in this._renderEffects) {
  56943. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56944. this._renderEffects[renderEffectName]._update();
  56945. }
  56946. }
  56947. for (var i = 0; i < this._cameras.length; i++) {
  56948. var cameraName = this._cameras[i].name;
  56949. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56950. this._renderEffectsForIsolatedPass[cameraName]._update();
  56951. }
  56952. }
  56953. };
  56954. PostProcessRenderPipeline.prototype._reset = function () {
  56955. this._renderEffects = {};
  56956. this._renderEffectsForIsolatedPass = new Array();
  56957. };
  56958. PostProcessRenderPipeline.prototype.dispose = function () {
  56959. // Must be implemented by children
  56960. };
  56961. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56962. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56963. __decorate([
  56964. BABYLON.serialize()
  56965. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56966. return PostProcessRenderPipeline;
  56967. }());
  56968. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56969. })(BABYLON || (BABYLON = {}));
  56970. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56971. var BABYLON;
  56972. (function (BABYLON) {
  56973. var DepthRenderer = /** @class */ (function () {
  56974. function DepthRenderer(scene, type) {
  56975. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56976. var _this = this;
  56977. this._scene = scene;
  56978. var engine = scene.getEngine();
  56979. // Render target
  56980. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56981. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56982. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56983. this._depthMap.refreshRate = 1;
  56984. this._depthMap.renderParticles = false;
  56985. this._depthMap.renderList = null;
  56986. // set default depth value to 1.0 (far away)
  56987. this._depthMap.onClearObservable.add(function (engine) {
  56988. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56989. });
  56990. // Custom render function
  56991. var renderSubMesh = function (subMesh) {
  56992. var mesh = subMesh.getRenderingMesh();
  56993. var scene = _this._scene;
  56994. var engine = scene.getEngine();
  56995. var material = subMesh.getMaterial();
  56996. if (!material) {
  56997. return;
  56998. }
  56999. // Culling
  57000. engine.setState(material.backFaceCulling);
  57001. // Managing instances
  57002. var batch = mesh._getInstancesRenderList(subMesh._id);
  57003. if (batch.mustReturn) {
  57004. return;
  57005. }
  57006. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57007. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57008. engine.enableEffect(_this._effect);
  57009. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57010. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57011. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57012. // Alpha test
  57013. if (material && material.needAlphaTesting()) {
  57014. var alphaTexture = material.getAlphaTestTexture();
  57015. if (alphaTexture) {
  57016. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57017. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57018. }
  57019. }
  57020. // Bones
  57021. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57022. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57023. }
  57024. // Draw
  57025. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57026. }
  57027. };
  57028. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57029. var index;
  57030. if (depthOnlySubMeshes.length) {
  57031. engine.setColorWrite(false);
  57032. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57033. renderSubMesh(depthOnlySubMeshes.data[index]);
  57034. }
  57035. engine.setColorWrite(true);
  57036. }
  57037. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57038. renderSubMesh(opaqueSubMeshes.data[index]);
  57039. }
  57040. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57041. renderSubMesh(alphaTestSubMeshes.data[index]);
  57042. }
  57043. };
  57044. }
  57045. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57046. var material = subMesh.getMaterial();
  57047. if (material.disableDepthWrite) {
  57048. return false;
  57049. }
  57050. var defines = [];
  57051. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57052. var mesh = subMesh.getMesh();
  57053. // Alpha test
  57054. if (material && material.needAlphaTesting()) {
  57055. defines.push("#define ALPHATEST");
  57056. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57057. attribs.push(BABYLON.VertexBuffer.UVKind);
  57058. defines.push("#define UV1");
  57059. }
  57060. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57061. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57062. defines.push("#define UV2");
  57063. }
  57064. }
  57065. // Bones
  57066. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57067. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57068. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57069. if (mesh.numBoneInfluencers > 4) {
  57070. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57071. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57072. }
  57073. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57074. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57075. }
  57076. else {
  57077. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57078. }
  57079. // Instances
  57080. if (useInstances) {
  57081. defines.push("#define INSTANCES");
  57082. attribs.push("world0");
  57083. attribs.push("world1");
  57084. attribs.push("world2");
  57085. attribs.push("world3");
  57086. }
  57087. // Get correct effect
  57088. var join = defines.join("\n");
  57089. if (this._cachedDefines !== join) {
  57090. this._cachedDefines = join;
  57091. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57092. }
  57093. return this._effect.isReady();
  57094. };
  57095. DepthRenderer.prototype.getDepthMap = function () {
  57096. return this._depthMap;
  57097. };
  57098. // Methods
  57099. DepthRenderer.prototype.dispose = function () {
  57100. this._depthMap.dispose();
  57101. };
  57102. return DepthRenderer;
  57103. }());
  57104. BABYLON.DepthRenderer = DepthRenderer;
  57105. })(BABYLON || (BABYLON = {}));
  57106. //# sourceMappingURL=babylon.depthRenderer.js.map
  57107. var BABYLON;
  57108. (function (BABYLON) {
  57109. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57110. __extends(SSAORenderingPipeline, _super);
  57111. /**
  57112. * @constructor
  57113. * @param {string} name - The rendering pipeline name
  57114. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57115. * @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 }
  57116. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57117. */
  57118. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57119. var _this = _super.call(this, scene.getEngine(), name) || this;
  57120. // Members
  57121. /**
  57122. * The PassPostProcess id in the pipeline that contains the original scene color
  57123. * @type {string}
  57124. */
  57125. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57126. /**
  57127. * The SSAO PostProcess id in the pipeline
  57128. * @type {string}
  57129. */
  57130. _this.SSAORenderEffect = "SSAORenderEffect";
  57131. /**
  57132. * The horizontal blur PostProcess id in the pipeline
  57133. * @type {string}
  57134. */
  57135. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57136. /**
  57137. * The vertical blur PostProcess id in the pipeline
  57138. * @type {string}
  57139. */
  57140. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57141. /**
  57142. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57143. * @type {string}
  57144. */
  57145. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57146. /**
  57147. * The output strength of the SSAO post-process. Default value is 1.0.
  57148. * @type {number}
  57149. */
  57150. _this.totalStrength = 1.0;
  57151. /**
  57152. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57153. * @type {number}
  57154. */
  57155. _this.radius = 0.0001;
  57156. /**
  57157. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57158. * Must not be equal to fallOff and superior to fallOff.
  57159. * Default value is 0.975
  57160. * @type {number}
  57161. */
  57162. _this.area = 0.0075;
  57163. /**
  57164. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57165. * Must not be equal to area and inferior to area.
  57166. * Default value is 0.0
  57167. * @type {number}
  57168. */
  57169. _this.fallOff = 0.000001;
  57170. /**
  57171. * The base color of the SSAO post-process
  57172. * The final result is "base + ssao" between [0, 1]
  57173. * @type {number}
  57174. */
  57175. _this.base = 0.5;
  57176. _this._firstUpdate = true;
  57177. _this._scene = scene;
  57178. // Set up assets
  57179. _this._createRandomTexture();
  57180. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57181. var ssaoRatio = ratio.ssaoRatio || ratio;
  57182. var combineRatio = ratio.combineRatio || ratio;
  57183. _this._ratio = {
  57184. ssaoRatio: ssaoRatio,
  57185. combineRatio: combineRatio
  57186. };
  57187. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57188. _this._createSSAOPostProcess(ssaoRatio);
  57189. _this._createBlurPostProcess(ssaoRatio);
  57190. _this._createSSAOCombinePostProcess(combineRatio);
  57191. // Set up pipeline
  57192. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57193. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57194. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57195. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57196. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57197. // Finish
  57198. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57199. if (cameras)
  57200. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57201. return _this;
  57202. }
  57203. // Public Methods
  57204. /**
  57205. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57206. */
  57207. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57208. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57209. for (var i = 0; i < this._scene.cameras.length; i++) {
  57210. var camera = this._scene.cameras[i];
  57211. this._originalColorPostProcess.dispose(camera);
  57212. this._ssaoPostProcess.dispose(camera);
  57213. this._blurHPostProcess.dispose(camera);
  57214. this._blurVPostProcess.dispose(camera);
  57215. this._ssaoCombinePostProcess.dispose(camera);
  57216. }
  57217. this._randomTexture.dispose();
  57218. if (disableDepthRender)
  57219. this._scene.disableDepthRenderer();
  57220. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57221. _super.prototype.dispose.call(this);
  57222. };
  57223. // Private Methods
  57224. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57225. var _this = this;
  57226. /*
  57227. var samplerOffsets = [
  57228. -8.0, -6.0, -4.0, -2.0,
  57229. 0.0,
  57230. 2.0, 4.0, 6.0, 8.0
  57231. ];
  57232. */
  57233. var samplerOffsets = new Array();
  57234. for (var i = -8; i < 8; i++) {
  57235. samplerOffsets.push(i * 2);
  57236. }
  57237. 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");
  57238. this._blurHPostProcess.onApply = function (effect) {
  57239. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57240. effect.setTexture("depthSampler", _this._depthTexture);
  57241. if (_this._firstUpdate) {
  57242. effect.setArray("samplerOffsets", samplerOffsets);
  57243. }
  57244. };
  57245. 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");
  57246. this._blurVPostProcess.onApply = function (effect) {
  57247. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57248. effect.setTexture("depthSampler", _this._depthTexture);
  57249. if (_this._firstUpdate) {
  57250. effect.setArray("samplerOffsets", samplerOffsets);
  57251. _this._firstUpdate = false;
  57252. }
  57253. };
  57254. };
  57255. SSAORenderingPipeline.prototype._rebuild = function () {
  57256. this._firstUpdate = true;
  57257. _super.prototype._rebuild.call(this);
  57258. };
  57259. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57260. var _this = this;
  57261. var numSamples = 16;
  57262. var sampleSphere = [
  57263. 0.5381, 0.1856, -0.4319,
  57264. 0.1379, 0.2486, 0.4430,
  57265. 0.3371, 0.5679, -0.0057,
  57266. -0.6999, -0.0451, -0.0019,
  57267. 0.0689, -0.1598, -0.8547,
  57268. 0.0560, 0.0069, -0.1843,
  57269. -0.0146, 0.1402, 0.0762,
  57270. 0.0100, -0.1924, -0.0344,
  57271. -0.3577, -0.5301, -0.4358,
  57272. -0.3169, 0.1063, 0.0158,
  57273. 0.0103, -0.5869, 0.0046,
  57274. -0.0897, -0.4940, 0.3287,
  57275. 0.7119, -0.0154, -0.0918,
  57276. -0.0533, 0.0596, -0.5411,
  57277. 0.0352, -0.0631, 0.5460,
  57278. -0.4776, 0.2847, -0.0271
  57279. ];
  57280. var samplesFactor = 1.0 / numSamples;
  57281. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57282. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57283. "area", "fallOff", "base", "range", "viewport"
  57284. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57285. this._ssaoPostProcess.onApply = function (effect) {
  57286. if (_this._firstUpdate) {
  57287. effect.setArray3("sampleSphere", sampleSphere);
  57288. effect.setFloat("samplesFactor", samplesFactor);
  57289. effect.setFloat("randTextureTiles", 4.0);
  57290. }
  57291. effect.setFloat("totalStrength", _this.totalStrength);
  57292. effect.setFloat("radius", _this.radius);
  57293. effect.setFloat("area", _this.area);
  57294. effect.setFloat("fallOff", _this.fallOff);
  57295. effect.setFloat("base", _this.base);
  57296. effect.setTexture("textureSampler", _this._depthTexture);
  57297. effect.setTexture("randomSampler", _this._randomTexture);
  57298. };
  57299. };
  57300. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57301. var _this = this;
  57302. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57303. this._ssaoCombinePostProcess.onApply = function (effect) {
  57304. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57305. };
  57306. };
  57307. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57308. var size = 512;
  57309. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57310. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57311. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57312. var context = this._randomTexture.getContext();
  57313. var rand = function (min, max) {
  57314. return Math.random() * (max - min) + min;
  57315. };
  57316. var randVector = BABYLON.Vector3.Zero();
  57317. for (var x = 0; x < size; x++) {
  57318. for (var y = 0; y < size; y++) {
  57319. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57320. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57321. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57322. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57323. context.fillRect(x, y, 1, 1);
  57324. }
  57325. }
  57326. this._randomTexture.update(false);
  57327. };
  57328. __decorate([
  57329. BABYLON.serialize()
  57330. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57331. __decorate([
  57332. BABYLON.serialize()
  57333. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57334. __decorate([
  57335. BABYLON.serialize()
  57336. ], SSAORenderingPipeline.prototype, "area", void 0);
  57337. __decorate([
  57338. BABYLON.serialize()
  57339. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57340. __decorate([
  57341. BABYLON.serialize()
  57342. ], SSAORenderingPipeline.prototype, "base", void 0);
  57343. __decorate([
  57344. BABYLON.serialize()
  57345. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57346. return SSAORenderingPipeline;
  57347. }(BABYLON.PostProcessRenderPipeline));
  57348. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57349. })(BABYLON || (BABYLON = {}));
  57350. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57351. var BABYLON;
  57352. (function (BABYLON) {
  57353. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57354. __extends(SSAO2RenderingPipeline, _super);
  57355. /**
  57356. * @constructor
  57357. * @param {string} name - The rendering pipeline name
  57358. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57359. * @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 }
  57360. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57361. */
  57362. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57363. var _this = _super.call(this, scene.getEngine(), name) || this;
  57364. // Members
  57365. /**
  57366. * The PassPostProcess id in the pipeline that contains the original scene color
  57367. * @type {string}
  57368. */
  57369. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57370. /**
  57371. * The SSAO PostProcess id in the pipeline
  57372. * @type {string}
  57373. */
  57374. _this.SSAORenderEffect = "SSAORenderEffect";
  57375. /**
  57376. * The horizontal blur PostProcess id in the pipeline
  57377. * @type {string}
  57378. */
  57379. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57380. /**
  57381. * The vertical blur PostProcess id in the pipeline
  57382. * @type {string}
  57383. */
  57384. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57385. /**
  57386. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57387. * @type {string}
  57388. */
  57389. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57390. /**
  57391. * The output strength of the SSAO post-process. Default value is 1.0.
  57392. * @type {number}
  57393. */
  57394. _this.totalStrength = 1.0;
  57395. /**
  57396. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57397. * @type {number}
  57398. */
  57399. _this.maxZ = 100.0;
  57400. /**
  57401. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57402. * @type {number}
  57403. */
  57404. _this.minZAspect = 0.2;
  57405. /**
  57406. * Number of samples used for the SSAO calculations. Default value is 8
  57407. * @type {number}
  57408. */
  57409. _this._samples = 8;
  57410. /**
  57411. * Are we using bilateral blur ?
  57412. * @type {boolean}
  57413. */
  57414. _this._expensiveBlur = true;
  57415. /**
  57416. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57417. * @type {number}
  57418. */
  57419. _this.radius = 2.0;
  57420. /**
  57421. * The base color of the SSAO post-process
  57422. * The final result is "base + ssao" between [0, 1]
  57423. * @type {number}
  57424. */
  57425. _this.base = 0.1;
  57426. _this._firstUpdate = true;
  57427. _this._scene = scene;
  57428. if (!_this.isSupported) {
  57429. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57430. return _this;
  57431. }
  57432. var ssaoRatio = ratio.ssaoRatio || ratio;
  57433. var blurRatio = ratio.blurRatio || ratio;
  57434. _this._ratio = {
  57435. ssaoRatio: ssaoRatio,
  57436. blurRatio: blurRatio
  57437. };
  57438. // Set up assets
  57439. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57440. _this._createRandomTexture();
  57441. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57442. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57443. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57444. _this._createSSAOPostProcess(1.0);
  57445. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57446. _this._createSSAOCombinePostProcess(blurRatio);
  57447. // Set up pipeline
  57448. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57449. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57450. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57451. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57452. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57453. // Finish
  57454. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57455. if (cameras)
  57456. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57457. return _this;
  57458. }
  57459. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57460. get: function () {
  57461. return this._samples;
  57462. },
  57463. set: function (n) {
  57464. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57465. this._samples = n;
  57466. this._sampleSphere = this._generateHemisphere();
  57467. this._firstUpdate = true;
  57468. },
  57469. enumerable: true,
  57470. configurable: true
  57471. });
  57472. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57473. get: function () {
  57474. return this._expensiveBlur;
  57475. },
  57476. set: function (b) {
  57477. 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"]);
  57478. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57479. this._expensiveBlur = b;
  57480. this._firstUpdate = true;
  57481. },
  57482. enumerable: true,
  57483. configurable: true
  57484. });
  57485. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57486. /**
  57487. * Support test.
  57488. * @type {boolean}
  57489. */
  57490. get: function () {
  57491. var engine = BABYLON.Engine.LastCreatedEngine;
  57492. if (!engine) {
  57493. return false;
  57494. }
  57495. return engine.getCaps().drawBuffersExtension;
  57496. },
  57497. enumerable: true,
  57498. configurable: true
  57499. });
  57500. // Public Methods
  57501. /**
  57502. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57503. */
  57504. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57505. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57506. for (var i = 0; i < this._scene.cameras.length; i++) {
  57507. var camera = this._scene.cameras[i];
  57508. this._originalColorPostProcess.dispose(camera);
  57509. this._ssaoPostProcess.dispose(camera);
  57510. this._blurHPostProcess.dispose(camera);
  57511. this._blurVPostProcess.dispose(camera);
  57512. this._ssaoCombinePostProcess.dispose(camera);
  57513. }
  57514. this._randomTexture.dispose();
  57515. if (disableGeometryBufferRenderer)
  57516. this._scene.disableGeometryBufferRenderer();
  57517. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57518. _super.prototype.dispose.call(this);
  57519. };
  57520. // Private Methods
  57521. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57522. var _this = this;
  57523. this._samplerOffsets = [];
  57524. var expensive = this.expensiveBlur;
  57525. for (var i = -8; i < 8; i++) {
  57526. this._samplerOffsets.push(i * 2 + 0.5);
  57527. }
  57528. 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");
  57529. this._blurHPostProcess.onApply = function (effect) {
  57530. if (!_this._scene.activeCamera) {
  57531. return;
  57532. }
  57533. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57534. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57535. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57536. effect.setFloat("radius", _this.radius);
  57537. effect.setTexture("depthSampler", _this._depthTexture);
  57538. if (_this._firstUpdate) {
  57539. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57540. }
  57541. };
  57542. 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");
  57543. this._blurVPostProcess.onApply = function (effect) {
  57544. if (!_this._scene.activeCamera) {
  57545. return;
  57546. }
  57547. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57548. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57549. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57550. effect.setFloat("radius", _this.radius);
  57551. effect.setTexture("depthSampler", _this._depthTexture);
  57552. if (_this._firstUpdate) {
  57553. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57554. _this._firstUpdate = false;
  57555. }
  57556. };
  57557. };
  57558. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57559. this._firstUpdate = true;
  57560. _super.prototype._rebuild.call(this);
  57561. };
  57562. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57563. var numSamples = this.samples;
  57564. var result = [];
  57565. var vector, scale;
  57566. var rand = function (min, max) {
  57567. return Math.random() * (max - min) + min;
  57568. };
  57569. var i = 0;
  57570. while (i < numSamples) {
  57571. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57572. vector.normalize();
  57573. scale = i / numSamples;
  57574. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57575. vector.scaleInPlace(scale);
  57576. result.push(vector.x, vector.y, vector.z);
  57577. i++;
  57578. }
  57579. return result;
  57580. };
  57581. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57582. var _this = this;
  57583. var numSamples = this.samples;
  57584. this._sampleSphere = this._generateHemisphere();
  57585. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57586. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57587. "base", "range", "projection", "near", "far", "texelSize",
  57588. "xViewport", "yViewport", "maxZ", "minZAspect"
  57589. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57590. this._ssaoPostProcess.onApply = function (effect) {
  57591. if (_this._firstUpdate) {
  57592. effect.setArray3("sampleSphere", _this._sampleSphere);
  57593. effect.setFloat("randTextureTiles", 4.0);
  57594. }
  57595. if (!_this._scene.activeCamera) {
  57596. return;
  57597. }
  57598. effect.setFloat("samplesFactor", 1 / _this.samples);
  57599. effect.setFloat("totalStrength", _this.totalStrength);
  57600. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57601. effect.setFloat("radius", _this.radius);
  57602. effect.setFloat("maxZ", _this.maxZ);
  57603. effect.setFloat("minZAspect", _this.minZAspect);
  57604. effect.setFloat("base", _this.base);
  57605. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57606. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57607. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57608. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57609. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57610. effect.setTexture("textureSampler", _this._depthTexture);
  57611. effect.setTexture("normalSampler", _this._normalTexture);
  57612. effect.setTexture("randomSampler", _this._randomTexture);
  57613. };
  57614. };
  57615. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57616. var _this = this;
  57617. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57618. this._ssaoCombinePostProcess.onApply = function (effect) {
  57619. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57620. };
  57621. };
  57622. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57623. var size = 512;
  57624. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57625. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57626. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57627. var context = this._randomTexture.getContext();
  57628. var rand = function (min, max) {
  57629. return Math.random() * (max - min) + min;
  57630. };
  57631. var randVector = BABYLON.Vector3.Zero();
  57632. for (var x = 0; x < size; x++) {
  57633. for (var y = 0; y < size; y++) {
  57634. randVector.x = rand(0.0, 1.0);
  57635. randVector.y = rand(0.0, 1.0);
  57636. randVector.z = 0.0;
  57637. randVector.normalize();
  57638. randVector.scaleInPlace(255);
  57639. randVector.x = Math.floor(randVector.x);
  57640. randVector.y = Math.floor(randVector.y);
  57641. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57642. context.fillRect(x, y, 1, 1);
  57643. }
  57644. }
  57645. this._randomTexture.update(false);
  57646. };
  57647. __decorate([
  57648. BABYLON.serialize()
  57649. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57650. __decorate([
  57651. BABYLON.serialize()
  57652. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57653. __decorate([
  57654. BABYLON.serialize()
  57655. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57656. __decorate([
  57657. BABYLON.serialize("samples")
  57658. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57659. __decorate([
  57660. BABYLON.serialize("expensiveBlur")
  57661. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57662. __decorate([
  57663. BABYLON.serialize()
  57664. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57665. __decorate([
  57666. BABYLON.serialize()
  57667. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57668. __decorate([
  57669. BABYLON.serialize()
  57670. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57671. return SSAO2RenderingPipeline;
  57672. }(BABYLON.PostProcessRenderPipeline));
  57673. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57674. })(BABYLON || (BABYLON = {}));
  57675. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57676. // BABYLON.JS Chromatic Aberration GLSL Shader
  57677. // Author: Olivier Guyot
  57678. // Separates very slightly R, G and B colors on the edges of the screen
  57679. // Inspired by Francois Tarlier & Martins Upitis
  57680. var BABYLON;
  57681. (function (BABYLON) {
  57682. var LensRenderingPipeline = /** @class */ (function (_super) {
  57683. __extends(LensRenderingPipeline, _super);
  57684. /**
  57685. * @constructor
  57686. *
  57687. * Effect parameters are as follow:
  57688. * {
  57689. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57690. * edge_blur: number; // from 0 to x (1 for realism)
  57691. * distortion: number; // from 0 to x (1 for realism)
  57692. * grain_amount: number; // from 0 to 1
  57693. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57694. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57695. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57696. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57697. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57698. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57699. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57700. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57701. * }
  57702. * Note: if an effect parameter is unset, effect is disabled
  57703. *
  57704. * @param {string} name - The rendering pipeline name
  57705. * @param {object} parameters - An object containing all parameters (see above)
  57706. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57707. * @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)
  57708. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57709. */
  57710. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57711. if (ratio === void 0) { ratio = 1.0; }
  57712. var _this = _super.call(this, scene.getEngine(), name) || this;
  57713. // Lens effects can be of the following:
  57714. // - chromatic aberration (slight shift of RGB colors)
  57715. // - blur on the edge of the lens
  57716. // - lens distortion
  57717. // - depth-of-field blur & highlights enhancing
  57718. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57719. // - grain effect (noise or custom texture)
  57720. // Two additional texture samplers are needed:
  57721. // - depth map (for depth-of-field)
  57722. // - grain texture
  57723. /**
  57724. * The chromatic aberration PostProcess id in the pipeline
  57725. * @type {string}
  57726. */
  57727. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57728. /**
  57729. * The highlights enhancing PostProcess id in the pipeline
  57730. * @type {string}
  57731. */
  57732. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57733. /**
  57734. * The depth-of-field PostProcess id in the pipeline
  57735. * @type {string}
  57736. */
  57737. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57738. _this._scene = scene;
  57739. // Fetch texture samplers
  57740. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57741. if (parameters.grain_texture) {
  57742. _this._grainTexture = parameters.grain_texture;
  57743. }
  57744. else {
  57745. _this._createGrainTexture();
  57746. }
  57747. // save parameters
  57748. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57749. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57750. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57751. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57752. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57753. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57754. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57755. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57756. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57757. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57758. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57759. // Create effects
  57760. _this._createChromaticAberrationPostProcess(ratio);
  57761. _this._createHighlightsPostProcess(ratio);
  57762. _this._createDepthOfFieldPostProcess(ratio / 4);
  57763. // Set up pipeline
  57764. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57766. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57767. if (_this._highlightsGain === -1) {
  57768. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57769. }
  57770. // Finish
  57771. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57772. if (cameras) {
  57773. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57774. }
  57775. return _this;
  57776. }
  57777. // public methods (self explanatory)
  57778. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57779. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57780. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57781. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57782. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57783. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57784. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57785. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57786. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57787. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57788. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57789. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57790. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57791. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57792. };
  57793. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57794. this._highlightsPostProcess.updateEffect();
  57795. };
  57796. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57797. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57798. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57799. this._highlightsGain = amount;
  57800. };
  57801. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57802. if (this._highlightsGain === -1) {
  57803. this._highlightsGain = 1.0;
  57804. }
  57805. this._highlightsThreshold = amount;
  57806. };
  57807. LensRenderingPipeline.prototype.disableHighlights = function () {
  57808. this._highlightsGain = -1;
  57809. };
  57810. /**
  57811. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57812. */
  57813. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57814. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57815. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57816. this._chromaticAberrationPostProcess = null;
  57817. this._highlightsPostProcess = null;
  57818. this._depthOfFieldPostProcess = null;
  57819. this._grainTexture.dispose();
  57820. if (disableDepthRender)
  57821. this._scene.disableDepthRenderer();
  57822. };
  57823. // colors shifting and distortion
  57824. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57825. var _this = this;
  57826. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57827. [], // samplers
  57828. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57829. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57830. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57831. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57832. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57833. };
  57834. };
  57835. // highlights enhancing
  57836. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57837. var _this = this;
  57838. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57839. [], // samplers
  57840. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57841. this._highlightsPostProcess.onApply = function (effect) {
  57842. effect.setFloat('gain', _this._highlightsGain);
  57843. effect.setFloat('threshold', _this._highlightsThreshold);
  57844. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57845. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57846. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57847. };
  57848. };
  57849. // colors shifting and distortion
  57850. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57851. var _this = this;
  57852. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57853. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57854. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57855. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57856. this._depthOfFieldPostProcess.onApply = function (effect) {
  57857. effect.setTexture("depthSampler", _this._depthTexture);
  57858. effect.setTexture("grainSampler", _this._grainTexture);
  57859. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57860. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57861. effect.setFloat('grain_amount', _this._grainAmount);
  57862. effect.setBool('blur_noise', _this._blurNoise);
  57863. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57864. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57865. effect.setFloat('distortion', _this._distortion);
  57866. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57867. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57868. effect.setFloat('aperture', _this._dofAperture);
  57869. effect.setFloat('darken', _this._dofDarken);
  57870. effect.setFloat('edge_blur', _this._edgeBlur);
  57871. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57872. if (_this._scene.activeCamera) {
  57873. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57874. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57875. }
  57876. };
  57877. };
  57878. // creates a black and white random noise texture, 512x512
  57879. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57880. var size = 512;
  57881. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57882. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57883. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57884. var context = this._grainTexture.getContext();
  57885. var rand = function (min, max) {
  57886. return Math.random() * (max - min) + min;
  57887. };
  57888. var value;
  57889. for (var x = 0; x < size; x++) {
  57890. for (var y = 0; y < size; y++) {
  57891. value = Math.floor(rand(0.42, 0.58) * 255);
  57892. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57893. context.fillRect(x, y, 1, 1);
  57894. }
  57895. }
  57896. this._grainTexture.update(false);
  57897. };
  57898. return LensRenderingPipeline;
  57899. }(BABYLON.PostProcessRenderPipeline));
  57900. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57901. })(BABYLON || (BABYLON = {}));
  57902. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57903. var BABYLON;
  57904. (function (BABYLON) {
  57905. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57906. __extends(StandardRenderingPipeline, _super);
  57907. /**
  57908. * @constructor
  57909. * @param {string} name - The rendering pipeline name
  57910. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57911. * @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)
  57912. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57913. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57914. */
  57915. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57916. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57917. var _this = _super.call(this, scene.getEngine(), name) || this;
  57918. _this.downSampleX4PostProcess = null;
  57919. _this.brightPassPostProcess = null;
  57920. _this.blurHPostProcesses = [];
  57921. _this.blurVPostProcesses = [];
  57922. _this.textureAdderPostProcess = null;
  57923. _this.volumetricLightPostProcess = null;
  57924. _this.volumetricLightSmoothXPostProcess = null;
  57925. _this.volumetricLightSmoothYPostProcess = null;
  57926. _this.volumetricLightMergePostProces = null;
  57927. _this.volumetricLightFinalPostProcess = null;
  57928. _this.luminancePostProcess = null;
  57929. _this.luminanceDownSamplePostProcesses = [];
  57930. _this.hdrPostProcess = null;
  57931. _this.textureAdderFinalPostProcess = null;
  57932. _this.lensFlareFinalPostProcess = null;
  57933. _this.hdrFinalPostProcess = null;
  57934. _this.lensFlarePostProcess = null;
  57935. _this.lensFlareComposePostProcess = null;
  57936. _this.motionBlurPostProcess = null;
  57937. _this.depthOfFieldPostProcess = null;
  57938. // Values
  57939. _this.brightThreshold = 1.0;
  57940. _this.blurWidth = 512.0;
  57941. _this.horizontalBlur = false;
  57942. _this.exposure = 1.0;
  57943. _this.lensTexture = null;
  57944. _this.volumetricLightCoefficient = 0.2;
  57945. _this.volumetricLightPower = 4.0;
  57946. _this.volumetricLightBlurScale = 64.0;
  57947. _this.sourceLight = null;
  57948. _this.hdrMinimumLuminance = 1.0;
  57949. _this.hdrDecreaseRate = 0.5;
  57950. _this.hdrIncreaseRate = 0.5;
  57951. _this.lensColorTexture = null;
  57952. _this.lensFlareStrength = 20.0;
  57953. _this.lensFlareGhostDispersal = 1.4;
  57954. _this.lensFlareHaloWidth = 0.7;
  57955. _this.lensFlareDistortionStrength = 16.0;
  57956. _this.lensStarTexture = null;
  57957. _this.lensFlareDirtTexture = null;
  57958. _this.depthOfFieldDistance = 10.0;
  57959. _this.depthOfFieldBlurWidth = 64.0;
  57960. _this.motionStrength = 1.0;
  57961. // IAnimatable
  57962. _this.animations = [];
  57963. _this._currentDepthOfFieldSource = null;
  57964. _this._hdrCurrentLuminance = 1.0;
  57965. // Getters and setters
  57966. _this._bloomEnabled = true;
  57967. _this._depthOfFieldEnabled = false;
  57968. _this._vlsEnabled = false;
  57969. _this._lensFlareEnabled = false;
  57970. _this._hdrEnabled = false;
  57971. _this._motionBlurEnabled = false;
  57972. _this._motionBlurSamples = 64.0;
  57973. _this._volumetricLightStepsCount = 50.0;
  57974. _this._cameras = cameras || [];
  57975. // Initialize
  57976. _this._scene = scene;
  57977. _this._basePostProcess = originalPostProcess;
  57978. _this._ratio = ratio;
  57979. // Misc
  57980. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57981. // Finish
  57982. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57983. _this._buildPipeline();
  57984. return _this;
  57985. }
  57986. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57987. get: function () {
  57988. return this._bloomEnabled;
  57989. },
  57990. set: function (enabled) {
  57991. if (this._bloomEnabled === enabled) {
  57992. return;
  57993. }
  57994. this._bloomEnabled = enabled;
  57995. this._buildPipeline();
  57996. },
  57997. enumerable: true,
  57998. configurable: true
  57999. });
  58000. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58001. get: function () {
  58002. return this._depthOfFieldEnabled;
  58003. },
  58004. set: function (enabled) {
  58005. if (this._depthOfFieldEnabled === enabled) {
  58006. return;
  58007. }
  58008. this._depthOfFieldEnabled = enabled;
  58009. this._buildPipeline();
  58010. },
  58011. enumerable: true,
  58012. configurable: true
  58013. });
  58014. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58015. get: function () {
  58016. return this._lensFlareEnabled;
  58017. },
  58018. set: function (enabled) {
  58019. if (this._lensFlareEnabled === enabled) {
  58020. return;
  58021. }
  58022. this._lensFlareEnabled = enabled;
  58023. this._buildPipeline();
  58024. },
  58025. enumerable: true,
  58026. configurable: true
  58027. });
  58028. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58029. get: function () {
  58030. return this._hdrEnabled;
  58031. },
  58032. set: function (enabled) {
  58033. if (this._hdrEnabled === enabled) {
  58034. return;
  58035. }
  58036. this._hdrEnabled = enabled;
  58037. this._buildPipeline();
  58038. },
  58039. enumerable: true,
  58040. configurable: true
  58041. });
  58042. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58043. get: function () {
  58044. return this._vlsEnabled;
  58045. },
  58046. set: function (enabled) {
  58047. if (this._vlsEnabled === enabled) {
  58048. return;
  58049. }
  58050. if (enabled) {
  58051. var geometry = this._scene.enableGeometryBufferRenderer();
  58052. if (!geometry) {
  58053. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58054. return;
  58055. }
  58056. }
  58057. this._vlsEnabled = enabled;
  58058. this._buildPipeline();
  58059. },
  58060. enumerable: true,
  58061. configurable: true
  58062. });
  58063. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58064. get: function () {
  58065. return this._motionBlurEnabled;
  58066. },
  58067. set: function (enabled) {
  58068. if (this._motionBlurEnabled === enabled) {
  58069. return;
  58070. }
  58071. this._motionBlurEnabled = enabled;
  58072. this._buildPipeline();
  58073. },
  58074. enumerable: true,
  58075. configurable: true
  58076. });
  58077. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58078. get: function () {
  58079. return this._volumetricLightStepsCount;
  58080. },
  58081. set: function (count) {
  58082. if (this.volumetricLightPostProcess) {
  58083. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58084. }
  58085. this._volumetricLightStepsCount = count;
  58086. },
  58087. enumerable: true,
  58088. configurable: true
  58089. });
  58090. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58091. get: function () {
  58092. return this._motionBlurSamples;
  58093. },
  58094. set: function (samples) {
  58095. if (this.motionBlurPostProcess) {
  58096. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58097. }
  58098. this._motionBlurSamples = samples;
  58099. },
  58100. enumerable: true,
  58101. configurable: true
  58102. });
  58103. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58104. var _this = this;
  58105. var ratio = this._ratio;
  58106. var scene = this._scene;
  58107. this._disposePostProcesses();
  58108. this._reset();
  58109. // Create pass post-process
  58110. if (!this._basePostProcess) {
  58111. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58112. this.originalPostProcess.onApply = function (effect) {
  58113. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58114. };
  58115. }
  58116. else {
  58117. this.originalPostProcess = this._basePostProcess;
  58118. }
  58119. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58120. this._currentDepthOfFieldSource = this.originalPostProcess;
  58121. if (this._vlsEnabled) {
  58122. // Create volumetric light
  58123. this._createVolumetricLightPostProcess(scene, ratio);
  58124. // Create volumetric light final post-process
  58125. 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);
  58126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58127. }
  58128. if (this._bloomEnabled) {
  58129. // Create down sample X4 post-process
  58130. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58131. // Create bright pass post-process
  58132. this._createBrightPassPostProcess(scene, ratio / 2);
  58133. // Create gaussian blur post-processes (down sampling blurs)
  58134. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58135. // Create texture adder post-process
  58136. this._createTextureAdderPostProcess(scene, ratio);
  58137. // Create depth-of-field source post-process
  58138. 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);
  58139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58140. }
  58141. if (this._lensFlareEnabled) {
  58142. // Create lens flare post-process
  58143. this._createLensFlarePostProcess(scene, ratio);
  58144. // Create depth-of-field source post-process post lens-flare and disable it now
  58145. 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);
  58146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58147. }
  58148. if (this._hdrEnabled) {
  58149. // Create luminance
  58150. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58151. // Create HDR
  58152. this._createHdrPostProcess(scene, ratio);
  58153. // Create depth-of-field source post-process post hdr and disable it now
  58154. 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);
  58155. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58156. }
  58157. if (this._depthOfFieldEnabled) {
  58158. // Create gaussian blur used by depth-of-field
  58159. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58160. // Create depth-of-field post-process
  58161. this._createDepthOfFieldPostProcess(scene, ratio);
  58162. }
  58163. if (this._motionBlurEnabled) {
  58164. // Create motion blur post-process
  58165. this._createMotionBlurPostProcess(scene, ratio);
  58166. }
  58167. if (this._cameras !== null) {
  58168. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58169. }
  58170. };
  58171. // Down Sample X4 Post-Processs
  58172. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58173. var _this = this;
  58174. var downSampleX4Offsets = new Array(32);
  58175. 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);
  58176. this.downSampleX4PostProcess.onApply = function (effect) {
  58177. var id = 0;
  58178. var width = _this.downSampleX4PostProcess.width;
  58179. var height = _this.downSampleX4PostProcess.height;
  58180. for (var i = -2; i < 2; i++) {
  58181. for (var j = -2; j < 2; j++) {
  58182. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58183. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58184. id += 2;
  58185. }
  58186. }
  58187. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58188. };
  58189. // Add to pipeline
  58190. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58191. };
  58192. // Brightpass Post-Process
  58193. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58194. var _this = this;
  58195. var brightOffsets = new Array(8);
  58196. 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);
  58197. this.brightPassPostProcess.onApply = function (effect) {
  58198. var sU = (1.0 / _this.brightPassPostProcess.width);
  58199. var sV = (1.0 / _this.brightPassPostProcess.height);
  58200. brightOffsets[0] = -0.5 * sU;
  58201. brightOffsets[1] = 0.5 * sV;
  58202. brightOffsets[2] = 0.5 * sU;
  58203. brightOffsets[3] = 0.5 * sV;
  58204. brightOffsets[4] = -0.5 * sU;
  58205. brightOffsets[5] = -0.5 * sV;
  58206. brightOffsets[6] = 0.5 * sU;
  58207. brightOffsets[7] = -0.5 * sV;
  58208. effect.setArray2("dsOffsets", brightOffsets);
  58209. effect.setFloat("brightThreshold", _this.brightThreshold);
  58210. };
  58211. // Add to pipeline
  58212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58213. };
  58214. // Create blur H&V post-processes
  58215. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58216. var _this = this;
  58217. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58218. var engine = scene.getEngine();
  58219. 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);
  58220. 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);
  58221. blurX.onActivateObservable.add(function () {
  58222. var dw = blurX.width / engine.getRenderWidth();
  58223. blurX.kernel = _this[blurWidthKey] * dw;
  58224. });
  58225. blurY.onActivateObservable.add(function () {
  58226. var dw = blurY.height / engine.getRenderHeight();
  58227. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58228. });
  58229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58231. this.blurHPostProcesses.push(blurX);
  58232. this.blurVPostProcesses.push(blurY);
  58233. };
  58234. // Create texture adder post-process
  58235. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58236. var _this = this;
  58237. 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);
  58238. this.textureAdderPostProcess.onApply = function (effect) {
  58239. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58240. effect.setTexture("lensSampler", _this.lensTexture);
  58241. effect.setFloat("exposure", _this.exposure);
  58242. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58243. };
  58244. // Add to pipeline
  58245. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58246. };
  58247. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58248. var _this = this;
  58249. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58250. geometryRenderer.enablePosition = true;
  58251. var geometry = geometryRenderer.getGBuffer();
  58252. // Base post-process
  58253. 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));
  58254. var depthValues = BABYLON.Vector2.Zero();
  58255. this.volumetricLightPostProcess.onApply = function (effect) {
  58256. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58257. var generator = _this.sourceLight.getShadowGenerator();
  58258. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58259. effect.setTexture("positionSampler", geometry.textures[2]);
  58260. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58261. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58262. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58263. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58264. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58265. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58266. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58267. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58268. effect.setVector2("depthValues", depthValues);
  58269. }
  58270. };
  58271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58272. // Smooth
  58273. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58274. // Merge
  58275. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58276. this.volumetricLightMergePostProces.onApply = function (effect) {
  58277. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58278. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58279. };
  58280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58281. };
  58282. // Create luminance
  58283. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58284. var _this = this;
  58285. // Create luminance
  58286. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58287. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58288. var offsets = [];
  58289. this.luminancePostProcess.onApply = function (effect) {
  58290. var sU = (1.0 / _this.luminancePostProcess.width);
  58291. var sV = (1.0 / _this.luminancePostProcess.height);
  58292. offsets[0] = -0.5 * sU;
  58293. offsets[1] = 0.5 * sV;
  58294. offsets[2] = 0.5 * sU;
  58295. offsets[3] = 0.5 * sV;
  58296. offsets[4] = -0.5 * sU;
  58297. offsets[5] = -0.5 * sV;
  58298. offsets[6] = 0.5 * sU;
  58299. offsets[7] = -0.5 * sV;
  58300. effect.setArray2("lumOffsets", offsets);
  58301. };
  58302. // Add to pipeline
  58303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58304. // Create down sample luminance
  58305. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58306. var size = Math.pow(3, i);
  58307. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58308. if (i === 0) {
  58309. defines += "#define FINAL_DOWN_SAMPLER";
  58310. }
  58311. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58312. this.luminanceDownSamplePostProcesses.push(postProcess);
  58313. }
  58314. // Create callbacks and add effects
  58315. var lastLuminance = this.luminancePostProcess;
  58316. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58317. var downSampleOffsets = new Array(18);
  58318. pp.onApply = function (effect) {
  58319. if (!lastLuminance) {
  58320. return;
  58321. }
  58322. var id = 0;
  58323. for (var x = -1; x < 2; x++) {
  58324. for (var y = -1; y < 2; y++) {
  58325. downSampleOffsets[id] = x / lastLuminance.width;
  58326. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58327. id += 2;
  58328. }
  58329. }
  58330. effect.setArray2("dsOffsets", downSampleOffsets);
  58331. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58332. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58333. lastLuminance = _this.luminancePostProcess;
  58334. }
  58335. else {
  58336. lastLuminance = pp;
  58337. }
  58338. };
  58339. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58340. pp.onAfterRender = function (effect) {
  58341. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58342. 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);
  58343. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58344. };
  58345. }
  58346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58347. });
  58348. };
  58349. // Create HDR post-process
  58350. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58351. var _this = this;
  58352. 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);
  58353. var outputLiminance = 1;
  58354. var time = 0;
  58355. var lastTime = 0;
  58356. this.hdrPostProcess.onApply = function (effect) {
  58357. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58358. time += scene.getEngine().getDeltaTime();
  58359. if (outputLiminance < 0) {
  58360. outputLiminance = _this._hdrCurrentLuminance;
  58361. }
  58362. else {
  58363. var dt = (lastTime - time) / 1000.0;
  58364. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58365. outputLiminance += _this.hdrDecreaseRate * dt;
  58366. }
  58367. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58368. outputLiminance -= _this.hdrIncreaseRate * dt;
  58369. }
  58370. else {
  58371. outputLiminance = _this._hdrCurrentLuminance;
  58372. }
  58373. }
  58374. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58375. effect.setFloat("averageLuminance", outputLiminance);
  58376. lastTime = time;
  58377. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58378. };
  58379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58380. };
  58381. // Create lens flare post-process
  58382. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58383. var _this = this;
  58384. 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);
  58385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58386. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58387. 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);
  58388. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58389. var resolution = new BABYLON.Vector2(0, 0);
  58390. // Lens flare
  58391. this.lensFlarePostProcess.onApply = function (effect) {
  58392. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58393. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58394. effect.setFloat("strength", _this.lensFlareStrength);
  58395. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58396. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58397. // Shift
  58398. resolution.x = _this.lensFlarePostProcess.width;
  58399. resolution.y = _this.lensFlarePostProcess.height;
  58400. effect.setVector2("resolution", resolution);
  58401. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58402. };
  58403. // Compose
  58404. 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);
  58405. 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);
  58406. this.lensFlareComposePostProcess.onApply = function (effect) {
  58407. if (!_this._scene.activeCamera) {
  58408. return;
  58409. }
  58410. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58411. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58412. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58413. // Lens start rotation matrix
  58414. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58415. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58416. 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));
  58417. camRot *= 4.0;
  58418. 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);
  58419. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58420. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58421. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58422. };
  58423. };
  58424. // Create depth-of-field post-process
  58425. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58426. var _this = this;
  58427. 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);
  58428. this.depthOfFieldPostProcess.onApply = function (effect) {
  58429. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58430. effect.setTexture("depthSampler", _this._getDepthTexture());
  58431. effect.setFloat("distance", _this.depthOfFieldDistance);
  58432. };
  58433. // Add to pipeline
  58434. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58435. };
  58436. // Create motion blur post-process
  58437. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58438. var _this = this;
  58439. 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);
  58440. var motionScale = 0;
  58441. var prevViewProjection = BABYLON.Matrix.Identity();
  58442. var invViewProjection = BABYLON.Matrix.Identity();
  58443. var viewProjection = BABYLON.Matrix.Identity();
  58444. var screenSize = BABYLON.Vector2.Zero();
  58445. this.motionBlurPostProcess.onApply = function (effect) {
  58446. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58447. viewProjection.invertToRef(invViewProjection);
  58448. effect.setMatrix("inverseViewProjection", invViewProjection);
  58449. effect.setMatrix("prevViewProjection", prevViewProjection);
  58450. prevViewProjection = viewProjection;
  58451. screenSize.x = _this.motionBlurPostProcess.width;
  58452. screenSize.y = _this.motionBlurPostProcess.height;
  58453. effect.setVector2("screenSize", screenSize);
  58454. motionScale = scene.getEngine().getFps() / 60.0;
  58455. effect.setFloat("motionScale", motionScale);
  58456. effect.setFloat("motionStrength", _this.motionStrength);
  58457. effect.setTexture("depthSampler", _this._getDepthTexture());
  58458. };
  58459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58460. };
  58461. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58462. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58463. var renderer = this._scene.enableGeometryBufferRenderer();
  58464. return renderer.getGBuffer().textures[0];
  58465. }
  58466. return this._scene.enableDepthRenderer().getDepthMap();
  58467. };
  58468. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58469. for (var i = 0; i < this._cameras.length; i++) {
  58470. var camera = this._cameras[i];
  58471. if (this.originalPostProcess) {
  58472. this.originalPostProcess.dispose(camera);
  58473. }
  58474. if (this.downSampleX4PostProcess) {
  58475. this.downSampleX4PostProcess.dispose(camera);
  58476. }
  58477. if (this.brightPassPostProcess) {
  58478. this.brightPassPostProcess.dispose(camera);
  58479. }
  58480. if (this.textureAdderPostProcess) {
  58481. this.textureAdderPostProcess.dispose(camera);
  58482. }
  58483. if (this.textureAdderFinalPostProcess) {
  58484. this.textureAdderFinalPostProcess.dispose(camera);
  58485. }
  58486. if (this.volumetricLightPostProcess) {
  58487. this.volumetricLightPostProcess.dispose(camera);
  58488. }
  58489. if (this.volumetricLightSmoothXPostProcess) {
  58490. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58491. }
  58492. if (this.volumetricLightSmoothYPostProcess) {
  58493. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58494. }
  58495. if (this.volumetricLightMergePostProces) {
  58496. this.volumetricLightMergePostProces.dispose(camera);
  58497. }
  58498. if (this.volumetricLightFinalPostProcess) {
  58499. this.volumetricLightFinalPostProcess.dispose(camera);
  58500. }
  58501. if (this.lensFlarePostProcess) {
  58502. this.lensFlarePostProcess.dispose(camera);
  58503. }
  58504. if (this.lensFlareComposePostProcess) {
  58505. this.lensFlareComposePostProcess.dispose(camera);
  58506. }
  58507. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58508. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58509. }
  58510. if (this.luminancePostProcess) {
  58511. this.luminancePostProcess.dispose(camera);
  58512. }
  58513. if (this.hdrPostProcess) {
  58514. this.hdrPostProcess.dispose(camera);
  58515. }
  58516. if (this.hdrFinalPostProcess) {
  58517. this.hdrFinalPostProcess.dispose(camera);
  58518. }
  58519. if (this.depthOfFieldPostProcess) {
  58520. this.depthOfFieldPostProcess.dispose(camera);
  58521. }
  58522. if (this.motionBlurPostProcess) {
  58523. this.motionBlurPostProcess.dispose(camera);
  58524. }
  58525. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58526. this.blurHPostProcesses[j].dispose(camera);
  58527. }
  58528. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58529. this.blurVPostProcesses[j].dispose(camera);
  58530. }
  58531. }
  58532. this.originalPostProcess = null;
  58533. this.downSampleX4PostProcess = null;
  58534. this.brightPassPostProcess = null;
  58535. this.textureAdderPostProcess = null;
  58536. this.textureAdderFinalPostProcess = null;
  58537. this.volumetricLightPostProcess = null;
  58538. this.volumetricLightSmoothXPostProcess = null;
  58539. this.volumetricLightSmoothYPostProcess = null;
  58540. this.volumetricLightMergePostProces = null;
  58541. this.volumetricLightFinalPostProcess = null;
  58542. this.lensFlarePostProcess = null;
  58543. this.lensFlareComposePostProcess = null;
  58544. this.luminancePostProcess = null;
  58545. this.hdrPostProcess = null;
  58546. this.hdrFinalPostProcess = null;
  58547. this.depthOfFieldPostProcess = null;
  58548. this.motionBlurPostProcess = null;
  58549. this.luminanceDownSamplePostProcesses = [];
  58550. this.blurHPostProcesses = [];
  58551. this.blurVPostProcesses = [];
  58552. };
  58553. // Dispose
  58554. StandardRenderingPipeline.prototype.dispose = function () {
  58555. this._disposePostProcesses();
  58556. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58557. _super.prototype.dispose.call(this);
  58558. };
  58559. // Serialize rendering pipeline
  58560. StandardRenderingPipeline.prototype.serialize = function () {
  58561. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58562. serializationObject.customType = "StandardRenderingPipeline";
  58563. return serializationObject;
  58564. };
  58565. /**
  58566. * Static members
  58567. */
  58568. // Parse serialized pipeline
  58569. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58570. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58571. };
  58572. // Luminance steps
  58573. StandardRenderingPipeline.LuminanceSteps = 6;
  58574. __decorate([
  58575. BABYLON.serialize()
  58576. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58577. __decorate([
  58578. BABYLON.serialize()
  58579. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58580. __decorate([
  58581. BABYLON.serialize()
  58582. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58583. __decorate([
  58584. BABYLON.serialize()
  58585. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58586. __decorate([
  58587. BABYLON.serializeAsTexture("lensTexture")
  58588. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58589. __decorate([
  58590. BABYLON.serialize()
  58591. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58592. __decorate([
  58593. BABYLON.serialize()
  58594. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58595. __decorate([
  58596. BABYLON.serialize()
  58597. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58598. __decorate([
  58599. BABYLON.serialize()
  58600. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58601. __decorate([
  58602. BABYLON.serialize()
  58603. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58604. __decorate([
  58605. BABYLON.serialize()
  58606. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58607. __decorate([
  58608. BABYLON.serializeAsTexture("lensColorTexture")
  58609. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58610. __decorate([
  58611. BABYLON.serialize()
  58612. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58613. __decorate([
  58614. BABYLON.serialize()
  58615. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58616. __decorate([
  58617. BABYLON.serialize()
  58618. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58619. __decorate([
  58620. BABYLON.serialize()
  58621. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58622. __decorate([
  58623. BABYLON.serializeAsTexture("lensStarTexture")
  58624. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58625. __decorate([
  58626. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58627. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58628. __decorate([
  58629. BABYLON.serialize()
  58630. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58631. __decorate([
  58632. BABYLON.serialize()
  58633. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58634. __decorate([
  58635. BABYLON.serialize()
  58636. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58637. __decorate([
  58638. BABYLON.serialize()
  58639. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58640. __decorate([
  58641. BABYLON.serialize()
  58642. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58643. __decorate([
  58644. BABYLON.serialize()
  58645. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58646. __decorate([
  58647. BABYLON.serialize()
  58648. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58649. __decorate([
  58650. BABYLON.serialize()
  58651. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58652. __decorate([
  58653. BABYLON.serialize()
  58654. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58655. __decorate([
  58656. BABYLON.serialize()
  58657. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58658. __decorate([
  58659. BABYLON.serialize()
  58660. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58661. return StandardRenderingPipeline;
  58662. }(BABYLON.PostProcessRenderPipeline));
  58663. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58664. })(BABYLON || (BABYLON = {}));
  58665. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58666. var BABYLON;
  58667. (function (BABYLON) {
  58668. var FxaaPostProcess = /** @class */ (function (_super) {
  58669. __extends(FxaaPostProcess, _super);
  58670. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58671. if (camera === void 0) { camera = null; }
  58672. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58673. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58674. _this.onApplyObservable.add(function (effect) {
  58675. var texelSize = _this.texelSize;
  58676. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58677. });
  58678. return _this;
  58679. }
  58680. return FxaaPostProcess;
  58681. }(BABYLON.PostProcess));
  58682. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58683. })(BABYLON || (BABYLON = {}));
  58684. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58685. var BABYLON;
  58686. (function (BABYLON) {
  58687. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58688. __extends(DefaultRenderingPipeline, _super);
  58689. /**
  58690. * @constructor
  58691. * @param {string} name - The rendering pipeline name
  58692. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58693. * @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)
  58694. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58695. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58696. */
  58697. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58698. if (automaticBuild === void 0) { automaticBuild = true; }
  58699. var _this = _super.call(this, scene.getEngine(), name) || this;
  58700. _this.PassPostProcessId = "PassPostProcessEffect";
  58701. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58702. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58703. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58704. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58705. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58706. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58707. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58708. // IAnimatable
  58709. _this.animations = [];
  58710. // Values
  58711. _this._bloomEnabled = false;
  58712. _this._fxaaEnabled = false;
  58713. _this._imageProcessingEnabled = true;
  58714. _this._bloomScale = 0.6;
  58715. _this._buildAllowed = true;
  58716. /**
  58717. * Specifies the size of the bloom blur kernel, relative to the final output size
  58718. */
  58719. _this.bloomKernel = 64;
  58720. /**
  58721. * Specifies the weight of the bloom in the final rendering
  58722. */
  58723. _this._bloomWeight = 0.15;
  58724. _this._cameras = cameras || [];
  58725. _this._buildAllowed = automaticBuild;
  58726. // Initialize
  58727. _this._scene = scene;
  58728. var caps = _this._scene.getEngine().getCaps();
  58729. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58730. // Misc
  58731. if (_this._hdr) {
  58732. if (caps.textureHalfFloatRender) {
  58733. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58734. }
  58735. else if (caps.textureFloatRender) {
  58736. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58737. }
  58738. }
  58739. else {
  58740. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58741. }
  58742. // Attach
  58743. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58744. _this._buildPipeline();
  58745. return _this;
  58746. }
  58747. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58748. get: function () {
  58749. return this._bloomWeight;
  58750. },
  58751. set: function (value) {
  58752. if (this._bloomWeight === value) {
  58753. return;
  58754. }
  58755. this._bloomWeight = value;
  58756. if (this._hdr && this.copyBack) {
  58757. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58758. }
  58759. },
  58760. enumerable: true,
  58761. configurable: true
  58762. });
  58763. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58764. get: function () {
  58765. return this._bloomScale;
  58766. },
  58767. set: function (value) {
  58768. if (this._bloomScale === value) {
  58769. return;
  58770. }
  58771. this._bloomScale = value;
  58772. this._buildPipeline();
  58773. },
  58774. enumerable: true,
  58775. configurable: true
  58776. });
  58777. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58778. get: function () {
  58779. return this._bloomEnabled;
  58780. },
  58781. set: function (enabled) {
  58782. if (this._bloomEnabled === enabled) {
  58783. return;
  58784. }
  58785. this._bloomEnabled = enabled;
  58786. this._buildPipeline();
  58787. },
  58788. enumerable: true,
  58789. configurable: true
  58790. });
  58791. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58792. get: function () {
  58793. return this._fxaaEnabled;
  58794. },
  58795. set: function (enabled) {
  58796. if (this._fxaaEnabled === enabled) {
  58797. return;
  58798. }
  58799. this._fxaaEnabled = enabled;
  58800. this._buildPipeline();
  58801. },
  58802. enumerable: true,
  58803. configurable: true
  58804. });
  58805. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58806. get: function () {
  58807. return this._imageProcessingEnabled;
  58808. },
  58809. set: function (enabled) {
  58810. if (this._imageProcessingEnabled === enabled) {
  58811. return;
  58812. }
  58813. this._imageProcessingEnabled = enabled;
  58814. this._buildPipeline();
  58815. },
  58816. enumerable: true,
  58817. configurable: true
  58818. });
  58819. /**
  58820. * Force the compilation of the entire pipeline.
  58821. */
  58822. DefaultRenderingPipeline.prototype.prepare = function () {
  58823. var previousState = this._buildAllowed;
  58824. this._buildAllowed = true;
  58825. this._buildPipeline();
  58826. this._buildAllowed = previousState;
  58827. };
  58828. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58829. var _this = this;
  58830. if (!this._buildAllowed) {
  58831. return;
  58832. }
  58833. var engine = this._scene.getEngine();
  58834. this._disposePostProcesses();
  58835. this._reset();
  58836. if (this.bloomEnabled) {
  58837. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58838. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58839. if (!this._hdr) {
  58840. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58841. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58842. this.highlights.autoClear = false;
  58843. this.highlights.alwaysForcePOT = true;
  58844. }
  58845. 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);
  58846. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58847. this.blurX.alwaysForcePOT = true;
  58848. this.blurX.autoClear = false;
  58849. this.blurX.onActivateObservable.add(function () {
  58850. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58851. _this.blurX.kernel = _this.bloomKernel * dw;
  58852. });
  58853. 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);
  58854. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58855. this.blurY.alwaysForcePOT = true;
  58856. this.blurY.autoClear = false;
  58857. this.blurY.onActivateObservable.add(function () {
  58858. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58859. _this.blurY.kernel = _this.bloomKernel * dh;
  58860. });
  58861. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58862. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58863. this.copyBack.alwaysForcePOT = true;
  58864. if (this._hdr) {
  58865. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58866. var w = this.bloomWeight;
  58867. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58868. }
  58869. else {
  58870. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58871. }
  58872. this.copyBack.autoClear = false;
  58873. }
  58874. if (this._imageProcessingEnabled) {
  58875. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58876. if (this._hdr) {
  58877. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58878. }
  58879. else {
  58880. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58881. }
  58882. }
  58883. if (this.fxaaEnabled) {
  58884. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58885. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58886. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58887. }
  58888. else {
  58889. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58890. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58891. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58892. }
  58893. if (this.bloomEnabled) {
  58894. if (this._hdr) {
  58895. this.copyBack.shareOutputWith(this.blurX);
  58896. if (this.imageProcessing) {
  58897. this.imageProcessing.shareOutputWith(this.pass);
  58898. this.imageProcessing.autoClear = false;
  58899. }
  58900. else if (this.fxaa) {
  58901. this.fxaa.shareOutputWith(this.pass);
  58902. }
  58903. else {
  58904. this.finalMerge.shareOutputWith(this.pass);
  58905. }
  58906. }
  58907. else {
  58908. if (this.fxaa) {
  58909. this.fxaa.shareOutputWith(this.pass);
  58910. }
  58911. else {
  58912. this.finalMerge.shareOutputWith(this.pass);
  58913. }
  58914. }
  58915. }
  58916. if (this._cameras !== null) {
  58917. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58918. }
  58919. };
  58920. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58921. for (var i = 0; i < this._cameras.length; i++) {
  58922. var camera = this._cameras[i];
  58923. if (this.pass) {
  58924. this.pass.dispose(camera);
  58925. }
  58926. if (this.highlights) {
  58927. this.highlights.dispose(camera);
  58928. }
  58929. if (this.blurX) {
  58930. this.blurX.dispose(camera);
  58931. }
  58932. if (this.blurY) {
  58933. this.blurY.dispose(camera);
  58934. }
  58935. if (this.copyBack) {
  58936. this.copyBack.dispose(camera);
  58937. }
  58938. if (this.imageProcessing) {
  58939. this.imageProcessing.dispose(camera);
  58940. }
  58941. if (this.fxaa) {
  58942. this.fxaa.dispose(camera);
  58943. }
  58944. if (this.finalMerge) {
  58945. this.finalMerge.dispose(camera);
  58946. }
  58947. }
  58948. this.pass = null;
  58949. this.highlights = null;
  58950. this.blurX = null;
  58951. this.blurY = null;
  58952. this.copyBack = null;
  58953. this.imageProcessing = null;
  58954. this.fxaa = null;
  58955. this.finalMerge = null;
  58956. };
  58957. // Dispose
  58958. DefaultRenderingPipeline.prototype.dispose = function () {
  58959. this._disposePostProcesses();
  58960. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58961. _super.prototype.dispose.call(this);
  58962. };
  58963. // Serialize rendering pipeline
  58964. DefaultRenderingPipeline.prototype.serialize = function () {
  58965. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58966. serializationObject.customType = "DefaultRenderingPipeline";
  58967. return serializationObject;
  58968. };
  58969. // Parse serialized pipeline
  58970. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58971. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58972. };
  58973. __decorate([
  58974. BABYLON.serialize()
  58975. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58976. __decorate([
  58977. BABYLON.serialize()
  58978. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58979. __decorate([
  58980. BABYLON.serialize()
  58981. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58982. __decorate([
  58983. BABYLON.serialize()
  58984. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58985. __decorate([
  58986. BABYLON.serialize()
  58987. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58988. __decorate([
  58989. BABYLON.serialize()
  58990. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58991. __decorate([
  58992. BABYLON.serialize()
  58993. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58994. __decorate([
  58995. BABYLON.serialize()
  58996. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58997. return DefaultRenderingPipeline;
  58998. }(BABYLON.PostProcessRenderPipeline));
  58999. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59000. })(BABYLON || (BABYLON = {}));
  59001. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59002. var BABYLON;
  59003. (function (BABYLON) {
  59004. var GeometryBufferRenderer = /** @class */ (function () {
  59005. function GeometryBufferRenderer(scene, ratio) {
  59006. if (ratio === void 0) { ratio = 1; }
  59007. this._enablePosition = false;
  59008. this._scene = scene;
  59009. this._ratio = ratio;
  59010. // Render target
  59011. this._createRenderTargets();
  59012. }
  59013. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59014. set: function (meshes) {
  59015. this._multiRenderTarget.renderList = meshes;
  59016. },
  59017. enumerable: true,
  59018. configurable: true
  59019. });
  59020. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59021. get: function () {
  59022. return this._multiRenderTarget.isSupported;
  59023. },
  59024. enumerable: true,
  59025. configurable: true
  59026. });
  59027. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59028. get: function () {
  59029. return this._enablePosition;
  59030. },
  59031. set: function (enable) {
  59032. this._enablePosition = enable;
  59033. this.dispose();
  59034. this._createRenderTargets();
  59035. },
  59036. enumerable: true,
  59037. configurable: true
  59038. });
  59039. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59040. var material = subMesh.getMaterial();
  59041. if (material && material.disableDepthWrite) {
  59042. return false;
  59043. }
  59044. var defines = [];
  59045. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59046. var mesh = subMesh.getMesh();
  59047. // Alpha test
  59048. if (material && material.needAlphaTesting()) {
  59049. defines.push("#define ALPHATEST");
  59050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59051. attribs.push(BABYLON.VertexBuffer.UVKind);
  59052. defines.push("#define UV1");
  59053. }
  59054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59055. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59056. defines.push("#define UV2");
  59057. }
  59058. }
  59059. // Buffers
  59060. if (this._enablePosition) {
  59061. defines.push("#define POSITION");
  59062. }
  59063. // Bones
  59064. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59065. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59066. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59067. if (mesh.numBoneInfluencers > 4) {
  59068. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59069. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59070. }
  59071. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59072. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59073. }
  59074. else {
  59075. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59076. }
  59077. // Instances
  59078. if (useInstances) {
  59079. defines.push("#define INSTANCES");
  59080. attribs.push("world0");
  59081. attribs.push("world1");
  59082. attribs.push("world2");
  59083. attribs.push("world3");
  59084. }
  59085. // Get correct effect
  59086. var join = defines.join("\n");
  59087. if (this._cachedDefines !== join) {
  59088. this._cachedDefines = join;
  59089. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59090. }
  59091. return this._effect.isReady();
  59092. };
  59093. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59094. return this._multiRenderTarget;
  59095. };
  59096. // Methods
  59097. GeometryBufferRenderer.prototype.dispose = function () {
  59098. this.getGBuffer().dispose();
  59099. };
  59100. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59101. var _this = this;
  59102. var engine = this._scene.getEngine();
  59103. var count = this._enablePosition ? 3 : 2;
  59104. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59105. if (!this.isSupported) {
  59106. return;
  59107. }
  59108. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59109. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59110. this._multiRenderTarget.refreshRate = 1;
  59111. this._multiRenderTarget.renderParticles = false;
  59112. this._multiRenderTarget.renderList = null;
  59113. // set default depth value to 1.0 (far away)
  59114. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59115. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59116. });
  59117. // Custom render function
  59118. var renderSubMesh = function (subMesh) {
  59119. var mesh = subMesh.getRenderingMesh();
  59120. var scene = _this._scene;
  59121. var engine = scene.getEngine();
  59122. var material = subMesh.getMaterial();
  59123. if (!material) {
  59124. return;
  59125. }
  59126. // Culling
  59127. engine.setState(material.backFaceCulling);
  59128. // Managing instances
  59129. var batch = mesh._getInstancesRenderList(subMesh._id);
  59130. if (batch.mustReturn) {
  59131. return;
  59132. }
  59133. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59134. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59135. engine.enableEffect(_this._effect);
  59136. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59137. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59138. _this._effect.setMatrix("view", scene.getViewMatrix());
  59139. // Alpha test
  59140. if (material && material.needAlphaTesting()) {
  59141. var alphaTexture = material.getAlphaTestTexture();
  59142. if (alphaTexture) {
  59143. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59144. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59145. }
  59146. }
  59147. // Bones
  59148. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59149. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59150. }
  59151. // Draw
  59152. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59153. }
  59154. };
  59155. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59156. var index;
  59157. if (depthOnlySubMeshes.length) {
  59158. engine.setColorWrite(false);
  59159. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59160. renderSubMesh(depthOnlySubMeshes.data[index]);
  59161. }
  59162. engine.setColorWrite(true);
  59163. }
  59164. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59165. renderSubMesh(opaqueSubMeshes.data[index]);
  59166. }
  59167. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59168. renderSubMesh(alphaTestSubMeshes.data[index]);
  59169. }
  59170. };
  59171. };
  59172. return GeometryBufferRenderer;
  59173. }());
  59174. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59175. })(BABYLON || (BABYLON = {}));
  59176. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59177. var BABYLON;
  59178. (function (BABYLON) {
  59179. var RefractionPostProcess = /** @class */ (function (_super) {
  59180. __extends(RefractionPostProcess, _super);
  59181. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59182. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59183. _this.color = color;
  59184. _this.depth = depth;
  59185. _this.colorLevel = colorLevel;
  59186. _this.onActivateObservable.add(function (cam) {
  59187. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59188. });
  59189. _this.onApplyObservable.add(function (effect) {
  59190. effect.setColor3("baseColor", _this.color);
  59191. effect.setFloat("depth", _this.depth);
  59192. effect.setFloat("colorLevel", _this.colorLevel);
  59193. effect.setTexture("refractionSampler", _this._refRexture);
  59194. });
  59195. return _this;
  59196. }
  59197. // Methods
  59198. RefractionPostProcess.prototype.dispose = function (camera) {
  59199. if (this._refRexture) {
  59200. this._refRexture.dispose();
  59201. }
  59202. _super.prototype.dispose.call(this, camera);
  59203. };
  59204. return RefractionPostProcess;
  59205. }(BABYLON.PostProcess));
  59206. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59207. })(BABYLON || (BABYLON = {}));
  59208. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59209. var BABYLON;
  59210. (function (BABYLON) {
  59211. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59212. __extends(BlackAndWhitePostProcess, _super);
  59213. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59214. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59215. _this.degree = 1;
  59216. _this.onApplyObservable.add(function (effect) {
  59217. effect.setFloat("degree", _this.degree);
  59218. });
  59219. return _this;
  59220. }
  59221. return BlackAndWhitePostProcess;
  59222. }(BABYLON.PostProcess));
  59223. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59224. })(BABYLON || (BABYLON = {}));
  59225. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59226. var BABYLON;
  59227. (function (BABYLON) {
  59228. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59229. __extends(ConvolutionPostProcess, _super);
  59230. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59231. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59232. _this.kernel = kernel;
  59233. _this.onApply = function (effect) {
  59234. effect.setFloat2("screenSize", _this.width, _this.height);
  59235. effect.setArray("kernel", _this.kernel);
  59236. };
  59237. return _this;
  59238. }
  59239. // Statics
  59240. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59241. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59242. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59243. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59244. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59245. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59246. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59247. return ConvolutionPostProcess;
  59248. }(BABYLON.PostProcess));
  59249. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59250. })(BABYLON || (BABYLON = {}));
  59251. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59252. var BABYLON;
  59253. (function (BABYLON) {
  59254. var FilterPostProcess = /** @class */ (function (_super) {
  59255. __extends(FilterPostProcess, _super);
  59256. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59257. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59258. _this.kernelMatrix = kernelMatrix;
  59259. _this.onApply = function (effect) {
  59260. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59261. };
  59262. return _this;
  59263. }
  59264. return FilterPostProcess;
  59265. }(BABYLON.PostProcess));
  59266. BABYLON.FilterPostProcess = FilterPostProcess;
  59267. })(BABYLON || (BABYLON = {}));
  59268. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59269. var BABYLON;
  59270. (function (BABYLON) {
  59271. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59272. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59273. __extends(VolumetricLightScatteringPostProcess, _super);
  59274. /**
  59275. * @constructor
  59276. * @param {string} name - The post-process name
  59277. * @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)
  59278. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59279. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59280. * @param {number} samples - The post-process quality, default 100
  59281. * @param {number} samplingMode - The post-process filtering mode
  59282. * @param {BABYLON.Engine} engine - The babylon engine
  59283. * @param {boolean} reusable - If the post-process is reusable
  59284. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59285. */
  59286. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59287. if (samples === void 0) { samples = 100; }
  59288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59289. 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;
  59290. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59291. /**
  59292. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59293. * @type {Vector3}
  59294. */
  59295. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59296. /**
  59297. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59298. * @type {boolean}
  59299. */
  59300. _this.useCustomMeshPosition = false;
  59301. /**
  59302. * If the post-process should inverse the light scattering direction
  59303. * @type {boolean}
  59304. */
  59305. _this.invert = true;
  59306. /**
  59307. * Array containing the excluded meshes not rendered in the internal pass
  59308. */
  59309. _this.excludedMeshes = new Array();
  59310. /**
  59311. * Controls the overall intensity of the post-process
  59312. * @type {number}
  59313. */
  59314. _this.exposure = 0.3;
  59315. /**
  59316. * Dissipates each sample's contribution in range [0, 1]
  59317. * @type {number}
  59318. */
  59319. _this.decay = 0.96815;
  59320. /**
  59321. * Controls the overall intensity of each sample
  59322. * @type {number}
  59323. */
  59324. _this.weight = 0.58767;
  59325. /**
  59326. * Controls the density of each sample
  59327. * @type {number}
  59328. */
  59329. _this.density = 0.926;
  59330. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59331. engine = scene.getEngine();
  59332. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59333. // Configure mesh
  59334. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59335. // Configure
  59336. _this._createPass(scene, ratio.passRatio || ratio);
  59337. _this.onActivate = function (camera) {
  59338. if (!_this.isSupported) {
  59339. _this.dispose(camera);
  59340. }
  59341. _this.onActivate = null;
  59342. };
  59343. _this.onApplyObservable.add(function (effect) {
  59344. _this._updateMeshScreenCoordinates(scene);
  59345. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59346. effect.setFloat("exposure", _this.exposure);
  59347. effect.setFloat("decay", _this.decay);
  59348. effect.setFloat("weight", _this.weight);
  59349. effect.setFloat("density", _this.density);
  59350. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59351. });
  59352. return _this;
  59353. }
  59354. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59355. get: function () {
  59356. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59357. return false;
  59358. },
  59359. set: function (useDiffuseColor) {
  59360. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59361. },
  59362. enumerable: true,
  59363. configurable: true
  59364. });
  59365. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59366. return "VolumetricLightScatteringPostProcess";
  59367. };
  59368. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59369. var mesh = subMesh.getMesh();
  59370. // Render this.mesh as default
  59371. if (mesh === this.mesh && mesh.material) {
  59372. return mesh.material.isReady(mesh);
  59373. }
  59374. var defines = [];
  59375. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59376. var material = subMesh.getMaterial();
  59377. // Alpha test
  59378. if (material) {
  59379. if (material.needAlphaTesting()) {
  59380. defines.push("#define ALPHATEST");
  59381. }
  59382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59383. attribs.push(BABYLON.VertexBuffer.UVKind);
  59384. defines.push("#define UV1");
  59385. }
  59386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59388. defines.push("#define UV2");
  59389. }
  59390. }
  59391. // Bones
  59392. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59395. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59396. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59397. }
  59398. else {
  59399. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59400. }
  59401. // Instances
  59402. if (useInstances) {
  59403. defines.push("#define INSTANCES");
  59404. attribs.push("world0");
  59405. attribs.push("world1");
  59406. attribs.push("world2");
  59407. attribs.push("world3");
  59408. }
  59409. // Get correct effect
  59410. var join = defines.join("\n");
  59411. if (this._cachedDefines !== join) {
  59412. this._cachedDefines = join;
  59413. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59414. }
  59415. return this._volumetricLightScatteringPass.isReady();
  59416. };
  59417. /**
  59418. * Sets the new light position for light scattering effect
  59419. * @param {BABYLON.Vector3} The new custom light position
  59420. */
  59421. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59422. this.customMeshPosition = position;
  59423. };
  59424. /**
  59425. * Returns the light position for light scattering effect
  59426. * @return {BABYLON.Vector3} The custom light position
  59427. */
  59428. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59429. return this.customMeshPosition;
  59430. };
  59431. /**
  59432. * Disposes the internal assets and detaches the post-process from the camera
  59433. */
  59434. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59435. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59436. if (rttIndex !== -1) {
  59437. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59438. }
  59439. this._volumetricLightScatteringRTT.dispose();
  59440. _super.prototype.dispose.call(this, camera);
  59441. };
  59442. /**
  59443. * Returns the render target texture used by the post-process
  59444. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59445. */
  59446. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59447. return this._volumetricLightScatteringRTT;
  59448. };
  59449. // Private methods
  59450. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59451. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59452. return true;
  59453. }
  59454. return false;
  59455. };
  59456. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59457. var _this = this;
  59458. var engine = scene.getEngine();
  59459. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59460. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59461. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59462. this._volumetricLightScatteringRTT.renderList = null;
  59463. this._volumetricLightScatteringRTT.renderParticles = false;
  59464. var camera = this.getCamera();
  59465. if (camera) {
  59466. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59467. }
  59468. else {
  59469. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59470. }
  59471. // Custom render function for submeshes
  59472. var renderSubMesh = function (subMesh) {
  59473. var mesh = subMesh.getRenderingMesh();
  59474. if (_this._meshExcluded(mesh)) {
  59475. return;
  59476. }
  59477. var material = subMesh.getMaterial();
  59478. if (!material) {
  59479. return;
  59480. }
  59481. var scene = mesh.getScene();
  59482. var engine = scene.getEngine();
  59483. // Culling
  59484. engine.setState(material.backFaceCulling);
  59485. // Managing instances
  59486. var batch = mesh._getInstancesRenderList(subMesh._id);
  59487. if (batch.mustReturn) {
  59488. return;
  59489. }
  59490. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59491. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59492. var effect = _this._volumetricLightScatteringPass;
  59493. if (mesh === _this.mesh) {
  59494. if (subMesh.effect) {
  59495. effect = subMesh.effect;
  59496. }
  59497. else {
  59498. effect = material.getEffect();
  59499. }
  59500. }
  59501. engine.enableEffect(effect);
  59502. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59503. if (mesh === _this.mesh) {
  59504. material.bind(mesh.getWorldMatrix(), mesh);
  59505. }
  59506. else {
  59507. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59508. // Alpha test
  59509. if (material && material.needAlphaTesting()) {
  59510. var alphaTexture = material.getAlphaTestTexture();
  59511. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59512. if (alphaTexture) {
  59513. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59514. }
  59515. }
  59516. // Bones
  59517. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59518. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59519. }
  59520. }
  59521. // Draw
  59522. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59523. }
  59524. };
  59525. // Render target texture callbacks
  59526. var savedSceneClearColor;
  59527. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59528. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59529. savedSceneClearColor = scene.clearColor;
  59530. scene.clearColor = sceneClearColor;
  59531. });
  59532. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59533. scene.clearColor = savedSceneClearColor;
  59534. });
  59535. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59536. var engine = scene.getEngine();
  59537. var index;
  59538. if (depthOnlySubMeshes.length) {
  59539. engine.setColorWrite(false);
  59540. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59541. renderSubMesh(depthOnlySubMeshes.data[index]);
  59542. }
  59543. engine.setColorWrite(true);
  59544. }
  59545. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59546. renderSubMesh(opaqueSubMeshes.data[index]);
  59547. }
  59548. engine.setAlphaTesting(true);
  59549. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59550. renderSubMesh(alphaTestSubMeshes.data[index]);
  59551. }
  59552. engine.setAlphaTesting(false);
  59553. if (transparentSubMeshes.length) {
  59554. // Sort sub meshes
  59555. for (index = 0; index < transparentSubMeshes.length; index++) {
  59556. var submesh = transparentSubMeshes.data[index];
  59557. var boundingInfo = submesh.getBoundingInfo();
  59558. if (boundingInfo && scene.activeCamera) {
  59559. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59560. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59561. }
  59562. }
  59563. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59564. sortedArray.sort(function (a, b) {
  59565. // Alpha index first
  59566. if (a._alphaIndex > b._alphaIndex) {
  59567. return 1;
  59568. }
  59569. if (a._alphaIndex < b._alphaIndex) {
  59570. return -1;
  59571. }
  59572. // Then distance to camera
  59573. if (a._distanceToCamera < b._distanceToCamera) {
  59574. return 1;
  59575. }
  59576. if (a._distanceToCamera > b._distanceToCamera) {
  59577. return -1;
  59578. }
  59579. return 0;
  59580. });
  59581. // Render sub meshes
  59582. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59583. for (index = 0; index < sortedArray.length; index++) {
  59584. renderSubMesh(sortedArray[index]);
  59585. }
  59586. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59587. }
  59588. };
  59589. };
  59590. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59591. var transform = scene.getTransformMatrix();
  59592. var meshPosition;
  59593. if (this.useCustomMeshPosition) {
  59594. meshPosition = this.customMeshPosition;
  59595. }
  59596. else if (this.attachedNode) {
  59597. meshPosition = this.attachedNode.position;
  59598. }
  59599. else {
  59600. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59601. }
  59602. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59603. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59604. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59605. if (this.invert)
  59606. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59607. };
  59608. // Static methods
  59609. /**
  59610. * Creates a default mesh for the Volumeric Light Scattering post-process
  59611. * @param {string} The mesh name
  59612. * @param {BABYLON.Scene} The scene where to create the mesh
  59613. * @return {BABYLON.Mesh} the default mesh
  59614. */
  59615. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59616. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59617. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59618. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59619. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59620. mesh.material = material;
  59621. return mesh;
  59622. };
  59623. __decorate([
  59624. BABYLON.serializeAsVector3()
  59625. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59626. __decorate([
  59627. BABYLON.serialize()
  59628. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59629. __decorate([
  59630. BABYLON.serialize()
  59631. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59632. __decorate([
  59633. BABYLON.serializeAsMeshReference()
  59634. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59635. __decorate([
  59636. BABYLON.serialize()
  59637. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59638. __decorate([
  59639. BABYLON.serialize()
  59640. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59641. __decorate([
  59642. BABYLON.serialize()
  59643. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59644. __decorate([
  59645. BABYLON.serialize()
  59646. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59647. __decorate([
  59648. BABYLON.serialize()
  59649. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59650. return VolumetricLightScatteringPostProcess;
  59651. }(BABYLON.PostProcess));
  59652. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59653. })(BABYLON || (BABYLON = {}));
  59654. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59655. //
  59656. // This post-process allows the modification of rendered colors by using
  59657. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59658. //
  59659. // The object needs to be provided an url to a texture containing the color
  59660. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59661. // Use an image editing software to tweak the LUT to match your needs.
  59662. //
  59663. // For an example of a color LUT, see here:
  59664. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59665. // For explanations on color grading, see here:
  59666. // http://udn.epicgames.com/Three/ColorGrading.html
  59667. //
  59668. var BABYLON;
  59669. (function (BABYLON) {
  59670. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59671. __extends(ColorCorrectionPostProcess, _super);
  59672. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59673. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59674. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59675. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59676. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59677. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59678. _this.onApply = function (effect) {
  59679. effect.setTexture("colorTable", _this._colorTableTexture);
  59680. };
  59681. return _this;
  59682. }
  59683. return ColorCorrectionPostProcess;
  59684. }(BABYLON.PostProcess));
  59685. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59686. })(BABYLON || (BABYLON = {}));
  59687. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59688. var BABYLON;
  59689. (function (BABYLON) {
  59690. var TonemappingOperator;
  59691. (function (TonemappingOperator) {
  59692. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59693. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59694. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59695. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59696. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59697. ;
  59698. var TonemapPostProcess = /** @class */ (function (_super) {
  59699. __extends(TonemapPostProcess, _super);
  59700. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59702. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59703. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59704. _this._operator = _operator;
  59705. _this.exposureAdjustment = exposureAdjustment;
  59706. var defines = "#define ";
  59707. if (_this._operator === TonemappingOperator.Hable)
  59708. defines += "HABLE_TONEMAPPING";
  59709. else if (_this._operator === TonemappingOperator.Reinhard)
  59710. defines += "REINHARD_TONEMAPPING";
  59711. else if (_this._operator === TonemappingOperator.HejiDawson)
  59712. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59713. else if (_this._operator === TonemappingOperator.Photographic)
  59714. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59715. //sadly a second call to create the effect.
  59716. _this.updateEffect(defines);
  59717. _this.onApply = function (effect) {
  59718. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59719. };
  59720. return _this;
  59721. }
  59722. return TonemapPostProcess;
  59723. }(BABYLON.PostProcess));
  59724. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59725. })(BABYLON || (BABYLON = {}));
  59726. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59727. var BABYLON;
  59728. (function (BABYLON) {
  59729. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59730. __extends(DisplayPassPostProcess, _super);
  59731. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59732. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59733. }
  59734. return DisplayPassPostProcess;
  59735. }(BABYLON.PostProcess));
  59736. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59737. })(BABYLON || (BABYLON = {}));
  59738. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59739. var BABYLON;
  59740. (function (BABYLON) {
  59741. var HighlightsPostProcess = /** @class */ (function (_super) {
  59742. __extends(HighlightsPostProcess, _super);
  59743. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59744. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59745. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59746. }
  59747. return HighlightsPostProcess;
  59748. }(BABYLON.PostProcess));
  59749. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59750. })(BABYLON || (BABYLON = {}));
  59751. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59752. var BABYLON;
  59753. (function (BABYLON) {
  59754. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59755. __extends(ImageProcessingPostProcess, _super);
  59756. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59757. if (camera === void 0) { camera = null; }
  59758. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59759. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59760. _this._fromLinearSpace = true;
  59761. /**
  59762. * Defines cache preventing GC.
  59763. */
  59764. _this._defines = {
  59765. IMAGEPROCESSING: false,
  59766. VIGNETTE: false,
  59767. VIGNETTEBLENDMODEMULTIPLY: false,
  59768. VIGNETTEBLENDMODEOPAQUE: false,
  59769. TONEMAPPING: false,
  59770. CONTRAST: false,
  59771. COLORCURVES: false,
  59772. COLORGRADING: false,
  59773. COLORGRADING3D: false,
  59774. FROMLINEARSPACE: false,
  59775. SAMPLER3DGREENDEPTH: false,
  59776. SAMPLER3DBGRMAP: false,
  59777. IMAGEPROCESSINGPOSTPROCESS: false,
  59778. EXPOSURE: false,
  59779. };
  59780. // Setup the default processing configuration to the scene.
  59781. _this._attachImageProcessingConfiguration(null, true);
  59782. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59783. _this.onApply = function (effect) {
  59784. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59785. };
  59786. return _this;
  59787. }
  59788. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59789. /**
  59790. * Gets the image processing configuration used either in this material.
  59791. */
  59792. get: function () {
  59793. return this._imageProcessingConfiguration;
  59794. },
  59795. /**
  59796. * Sets the Default image processing configuration used either in the this material.
  59797. *
  59798. * If sets to null, the scene one is in use.
  59799. */
  59800. set: function (value) {
  59801. this._attachImageProcessingConfiguration(value);
  59802. },
  59803. enumerable: true,
  59804. configurable: true
  59805. });
  59806. /**
  59807. * Attaches a new image processing configuration to the PBR Material.
  59808. * @param configuration
  59809. */
  59810. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59811. var _this = this;
  59812. if (doNotBuild === void 0) { doNotBuild = false; }
  59813. if (configuration === this._imageProcessingConfiguration) {
  59814. return;
  59815. }
  59816. // Detaches observer.
  59817. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59818. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59819. }
  59820. // Pick the scene configuration if needed.
  59821. if (!configuration) {
  59822. var scene = null;
  59823. var engine = this.getEngine();
  59824. var camera = this.getCamera();
  59825. if (camera) {
  59826. scene = camera.getScene();
  59827. }
  59828. else if (engine && engine.scenes) {
  59829. var scenes = engine.scenes;
  59830. scene = scenes[scenes.length - 1];
  59831. }
  59832. else {
  59833. scene = BABYLON.Engine.LastCreatedScene;
  59834. }
  59835. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59836. }
  59837. else {
  59838. this._imageProcessingConfiguration = configuration;
  59839. }
  59840. // Attaches observer.
  59841. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59842. _this._updateParameters();
  59843. });
  59844. // Ensure the effect will be rebuilt.
  59845. if (!doNotBuild) {
  59846. this._updateParameters();
  59847. }
  59848. };
  59849. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59850. /**
  59851. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59852. */
  59853. get: function () {
  59854. return this.imageProcessingConfiguration.colorCurves;
  59855. },
  59856. /**
  59857. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59858. */
  59859. set: function (value) {
  59860. this.imageProcessingConfiguration.colorCurves = value;
  59861. },
  59862. enumerable: true,
  59863. configurable: true
  59864. });
  59865. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59866. /**
  59867. * Gets wether the color curves effect is enabled.
  59868. */
  59869. get: function () {
  59870. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59871. },
  59872. /**
  59873. * Sets wether the color curves effect is enabled.
  59874. */
  59875. set: function (value) {
  59876. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59877. },
  59878. enumerable: true,
  59879. configurable: true
  59880. });
  59881. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59882. /**
  59883. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59884. */
  59885. get: function () {
  59886. return this.imageProcessingConfiguration.colorGradingTexture;
  59887. },
  59888. /**
  59889. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59890. */
  59891. set: function (value) {
  59892. this.imageProcessingConfiguration.colorGradingTexture = value;
  59893. },
  59894. enumerable: true,
  59895. configurable: true
  59896. });
  59897. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59898. /**
  59899. * Gets wether the color grading effect is enabled.
  59900. */
  59901. get: function () {
  59902. return this.imageProcessingConfiguration.colorGradingEnabled;
  59903. },
  59904. /**
  59905. * Gets wether the color grading effect is enabled.
  59906. */
  59907. set: function (value) {
  59908. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59909. },
  59910. enumerable: true,
  59911. configurable: true
  59912. });
  59913. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59914. /**
  59915. * Gets exposure used in the effect.
  59916. */
  59917. get: function () {
  59918. return this.imageProcessingConfiguration.exposure;
  59919. },
  59920. /**
  59921. * Sets exposure used in the effect.
  59922. */
  59923. set: function (value) {
  59924. this.imageProcessingConfiguration.exposure = value;
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59930. /**
  59931. * Gets wether tonemapping is enabled or not.
  59932. */
  59933. get: function () {
  59934. return this._imageProcessingConfiguration.toneMappingEnabled;
  59935. },
  59936. /**
  59937. * Sets wether tonemapping is enabled or not
  59938. */
  59939. set: function (value) {
  59940. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59941. },
  59942. enumerable: true,
  59943. configurable: true
  59944. });
  59945. ;
  59946. ;
  59947. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59948. /**
  59949. * Gets contrast used in the effect.
  59950. */
  59951. get: function () {
  59952. return this.imageProcessingConfiguration.contrast;
  59953. },
  59954. /**
  59955. * Sets contrast used in the effect.
  59956. */
  59957. set: function (value) {
  59958. this.imageProcessingConfiguration.contrast = value;
  59959. },
  59960. enumerable: true,
  59961. configurable: true
  59962. });
  59963. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59964. /**
  59965. * Gets Vignette stretch size.
  59966. */
  59967. get: function () {
  59968. return this.imageProcessingConfiguration.vignetteStretch;
  59969. },
  59970. /**
  59971. * Sets Vignette stretch size.
  59972. */
  59973. set: function (value) {
  59974. this.imageProcessingConfiguration.vignetteStretch = value;
  59975. },
  59976. enumerable: true,
  59977. configurable: true
  59978. });
  59979. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59980. /**
  59981. * Gets Vignette centre X Offset.
  59982. */
  59983. get: function () {
  59984. return this.imageProcessingConfiguration.vignetteCentreX;
  59985. },
  59986. /**
  59987. * Sets Vignette centre X Offset.
  59988. */
  59989. set: function (value) {
  59990. this.imageProcessingConfiguration.vignetteCentreX = value;
  59991. },
  59992. enumerable: true,
  59993. configurable: true
  59994. });
  59995. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59996. /**
  59997. * Gets Vignette centre Y Offset.
  59998. */
  59999. get: function () {
  60000. return this.imageProcessingConfiguration.vignetteCentreY;
  60001. },
  60002. /**
  60003. * Sets Vignette centre Y Offset.
  60004. */
  60005. set: function (value) {
  60006. this.imageProcessingConfiguration.vignetteCentreY = value;
  60007. },
  60008. enumerable: true,
  60009. configurable: true
  60010. });
  60011. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60012. /**
  60013. * Gets Vignette weight or intensity of the vignette effect.
  60014. */
  60015. get: function () {
  60016. return this.imageProcessingConfiguration.vignetteWeight;
  60017. },
  60018. /**
  60019. * Sets Vignette weight or intensity of the vignette effect.
  60020. */
  60021. set: function (value) {
  60022. this.imageProcessingConfiguration.vignetteWeight = value;
  60023. },
  60024. enumerable: true,
  60025. configurable: true
  60026. });
  60027. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60028. /**
  60029. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60030. * if vignetteEnabled is set to true.
  60031. */
  60032. get: function () {
  60033. return this.imageProcessingConfiguration.vignetteColor;
  60034. },
  60035. /**
  60036. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60037. * if vignetteEnabled is set to true.
  60038. */
  60039. set: function (value) {
  60040. this.imageProcessingConfiguration.vignetteColor = value;
  60041. },
  60042. enumerable: true,
  60043. configurable: true
  60044. });
  60045. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60046. /**
  60047. * Gets Camera field of view used by the Vignette effect.
  60048. */
  60049. get: function () {
  60050. return this.imageProcessingConfiguration.vignetteCameraFov;
  60051. },
  60052. /**
  60053. * Sets Camera field of view used by the Vignette effect.
  60054. */
  60055. set: function (value) {
  60056. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60057. },
  60058. enumerable: true,
  60059. configurable: true
  60060. });
  60061. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60062. /**
  60063. * Gets the vignette blend mode allowing different kind of effect.
  60064. */
  60065. get: function () {
  60066. return this.imageProcessingConfiguration.vignetteBlendMode;
  60067. },
  60068. /**
  60069. * Sets the vignette blend mode allowing different kind of effect.
  60070. */
  60071. set: function (value) {
  60072. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60073. },
  60074. enumerable: true,
  60075. configurable: true
  60076. });
  60077. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60078. /**
  60079. * Gets wether the vignette effect is enabled.
  60080. */
  60081. get: function () {
  60082. return this.imageProcessingConfiguration.vignetteEnabled;
  60083. },
  60084. /**
  60085. * Sets wether the vignette effect is enabled.
  60086. */
  60087. set: function (value) {
  60088. this.imageProcessingConfiguration.vignetteEnabled = value;
  60089. },
  60090. enumerable: true,
  60091. configurable: true
  60092. });
  60093. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60094. /**
  60095. * Gets wether the input of the processing is in Gamma or Linear Space.
  60096. */
  60097. get: function () {
  60098. return this._fromLinearSpace;
  60099. },
  60100. /**
  60101. * Sets wether the input of the processing is in Gamma or Linear Space.
  60102. */
  60103. set: function (value) {
  60104. if (this._fromLinearSpace === value) {
  60105. return;
  60106. }
  60107. this._fromLinearSpace = value;
  60108. this._updateParameters();
  60109. },
  60110. enumerable: true,
  60111. configurable: true
  60112. });
  60113. ImageProcessingPostProcess.prototype.getClassName = function () {
  60114. return "ImageProcessingPostProcess";
  60115. };
  60116. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60117. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60118. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60119. var defines = "";
  60120. for (var define in this._defines) {
  60121. if (this._defines[define]) {
  60122. defines += "#define " + define + ";\r\n";
  60123. }
  60124. }
  60125. var samplers = ["textureSampler"];
  60126. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60127. var uniforms = ["scale"];
  60128. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60129. this.updateEffect(defines, uniforms, samplers);
  60130. };
  60131. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60132. _super.prototype.dispose.call(this, camera);
  60133. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60134. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60135. }
  60136. this.imageProcessingConfiguration.applyByPostProcess = false;
  60137. };
  60138. __decorate([
  60139. BABYLON.serialize()
  60140. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60141. return ImageProcessingPostProcess;
  60142. }(BABYLON.PostProcess));
  60143. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60144. })(BABYLON || (BABYLON = {}));
  60145. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60146. var BABYLON;
  60147. (function (BABYLON) {
  60148. var BlurPostProcess = /** @class */ (function (_super) {
  60149. __extends(BlurPostProcess, _super);
  60150. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60152. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60153. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60154. _this.direction = direction;
  60155. _this._packedFloat = false;
  60156. _this.onApplyObservable.add(function (effect) {
  60157. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60158. });
  60159. _this.kernel = kernel;
  60160. return _this;
  60161. }
  60162. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60163. /**
  60164. * Gets the length in pixels of the blur sample region
  60165. */
  60166. get: function () {
  60167. return this._idealKernel;
  60168. },
  60169. /**
  60170. * Sets the length in pixels of the blur sample region
  60171. */
  60172. set: function (v) {
  60173. if (this._idealKernel === v) {
  60174. return;
  60175. }
  60176. v = Math.max(v, 1);
  60177. this._idealKernel = v;
  60178. this._kernel = this._nearestBestKernel(v);
  60179. this._updateParameters();
  60180. },
  60181. enumerable: true,
  60182. configurable: true
  60183. });
  60184. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60185. /**
  60186. * Gets wether or not the blur is unpacking/repacking floats
  60187. */
  60188. get: function () {
  60189. return this._packedFloat;
  60190. },
  60191. /**
  60192. * Sets wether or not the blur needs to unpack/repack floats
  60193. */
  60194. set: function (v) {
  60195. if (this._packedFloat === v) {
  60196. return;
  60197. }
  60198. this._packedFloat = v;
  60199. this._updateParameters();
  60200. },
  60201. enumerable: true,
  60202. configurable: true
  60203. });
  60204. BlurPostProcess.prototype._updateParameters = function () {
  60205. // Generate sampling offsets and weights
  60206. var N = this._kernel;
  60207. var centerIndex = (N - 1) / 2;
  60208. // Generate Gaussian sampling weights over kernel
  60209. var offsets = [];
  60210. var weights = [];
  60211. var totalWeight = 0;
  60212. for (var i = 0; i < N; i++) {
  60213. var u = i / (N - 1);
  60214. var w = this._gaussianWeight(u * 2.0 - 1);
  60215. offsets[i] = (i - centerIndex);
  60216. weights[i] = w;
  60217. totalWeight += w;
  60218. }
  60219. // Normalize weights
  60220. for (var i = 0; i < weights.length; i++) {
  60221. weights[i] /= totalWeight;
  60222. }
  60223. // Optimize: combine samples to take advantage of hardware linear sampling
  60224. // Walk from left to center, combining pairs (symmetrically)
  60225. var linearSamplingWeights = [];
  60226. var linearSamplingOffsets = [];
  60227. var linearSamplingMap = [];
  60228. for (var i = 0; i <= centerIndex; i += 2) {
  60229. var j = Math.min(i + 1, Math.floor(centerIndex));
  60230. var singleCenterSample = i === j;
  60231. if (singleCenterSample) {
  60232. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60233. }
  60234. else {
  60235. var sharedCell = j === centerIndex;
  60236. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60237. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60238. if (offsetLinear === 0) {
  60239. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60240. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60241. }
  60242. else {
  60243. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60244. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60245. }
  60246. }
  60247. }
  60248. for (var i = 0; i < linearSamplingMap.length; i++) {
  60249. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60250. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60251. }
  60252. // Replace with optimized
  60253. offsets = linearSamplingOffsets;
  60254. weights = linearSamplingWeights;
  60255. // Generate shaders
  60256. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60257. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60258. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60259. var defines = "";
  60260. for (var i = 0; i < varyingCount; i++) {
  60261. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60262. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60263. }
  60264. var depCount = 0;
  60265. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60266. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60267. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60268. depCount++;
  60269. }
  60270. if (this.packedFloat) {
  60271. defines += "#define PACKEDFLOAT 1";
  60272. }
  60273. this.updateEffect(defines, null, null, {
  60274. varyingCount: varyingCount,
  60275. depCount: depCount
  60276. });
  60277. };
  60278. /**
  60279. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60280. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60281. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60282. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60283. * The gaps between physical kernels are compensated for in the weighting of the samples
  60284. * @param idealKernel Ideal blur kernel.
  60285. * @return Nearest best kernel.
  60286. */
  60287. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60288. var v = Math.round(idealKernel);
  60289. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60290. var k = _a[_i];
  60291. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60292. return Math.max(k, 3);
  60293. }
  60294. }
  60295. return Math.max(v, 3);
  60296. };
  60297. /**
  60298. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60299. * @param x The point on the Gaussian distribution to sample.
  60300. * @return the value of the Gaussian function at x.
  60301. */
  60302. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60303. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60304. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60305. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60306. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60307. // truncated at around 1.3% of peak strength.
  60308. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60309. var sigma = (1 / 3);
  60310. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60311. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60312. var weight = (1.0 / denominator) * Math.exp(exponent);
  60313. return weight;
  60314. };
  60315. /**
  60316. * Generates a string that can be used as a floating point number in GLSL.
  60317. * @param x Value to print.
  60318. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60319. * @return GLSL float string.
  60320. */
  60321. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60322. if (decimalFigures === void 0) { decimalFigures = 8; }
  60323. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60324. };
  60325. return BlurPostProcess;
  60326. }(BABYLON.PostProcess));
  60327. BABYLON.BlurPostProcess = BlurPostProcess;
  60328. })(BABYLON || (BABYLON = {}));
  60329. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60330. var BABYLON;
  60331. (function (BABYLON) {
  60332. var Bone = /** @class */ (function (_super) {
  60333. __extends(Bone, _super);
  60334. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60335. if (parentBone === void 0) { parentBone = null; }
  60336. if (localMatrix === void 0) { localMatrix = null; }
  60337. if (restPose === void 0) { restPose = null; }
  60338. if (baseMatrix === void 0) { baseMatrix = null; }
  60339. if (index === void 0) { index = null; }
  60340. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60341. _this.name = name;
  60342. _this.children = new Array();
  60343. _this.animations = new Array();
  60344. // Set this value to map this bone to a different index in the transform matrices.
  60345. // Set this value to -1 to exclude the bone from the transform matrices.
  60346. _this._index = null;
  60347. _this._worldTransform = new BABYLON.Matrix();
  60348. _this._absoluteTransform = new BABYLON.Matrix();
  60349. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60350. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60351. _this._scaleVector = BABYLON.Vector3.One();
  60352. _this._negateScaleChildren = BABYLON.Vector3.One();
  60353. _this._scalingDeterminant = 1;
  60354. _this._skeleton = skeleton;
  60355. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60356. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60357. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60358. _this._index = index;
  60359. skeleton.bones.push(_this);
  60360. _this.setParent(parentBone, false);
  60361. _this._updateDifferenceMatrix();
  60362. return _this;
  60363. }
  60364. Object.defineProperty(Bone.prototype, "_matrix", {
  60365. get: function () {
  60366. return this._localMatrix;
  60367. },
  60368. set: function (val) {
  60369. if (this._localMatrix) {
  60370. this._localMatrix.copyFrom(val);
  60371. }
  60372. else {
  60373. this._localMatrix = val;
  60374. }
  60375. },
  60376. enumerable: true,
  60377. configurable: true
  60378. });
  60379. // Members
  60380. Bone.prototype.getSkeleton = function () {
  60381. return this._skeleton;
  60382. };
  60383. Bone.prototype.getParent = function () {
  60384. return this._parent;
  60385. };
  60386. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60387. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60388. if (this._parent === parent) {
  60389. return;
  60390. }
  60391. if (this._parent) {
  60392. var index = this._parent.children.indexOf(this);
  60393. if (index !== -1) {
  60394. this._parent.children.splice(index, 1);
  60395. }
  60396. }
  60397. this._parent = parent;
  60398. if (this._parent) {
  60399. this._parent.children.push(this);
  60400. }
  60401. if (updateDifferenceMatrix) {
  60402. this._updateDifferenceMatrix();
  60403. }
  60404. };
  60405. Bone.prototype.getLocalMatrix = function () {
  60406. return this._localMatrix;
  60407. };
  60408. Bone.prototype.getBaseMatrix = function () {
  60409. return this._baseMatrix;
  60410. };
  60411. Bone.prototype.getRestPose = function () {
  60412. return this._restPose;
  60413. };
  60414. Bone.prototype.returnToRest = function () {
  60415. this.updateMatrix(this._restPose.clone());
  60416. };
  60417. Bone.prototype.getWorldMatrix = function () {
  60418. return this._worldTransform;
  60419. };
  60420. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60421. return this._invertedAbsoluteTransform;
  60422. };
  60423. Bone.prototype.getAbsoluteTransform = function () {
  60424. return this._absoluteTransform;
  60425. };
  60426. Object.defineProperty(Bone.prototype, "position", {
  60427. // Properties (matches AbstractMesh properties)
  60428. get: function () {
  60429. return this.getPosition();
  60430. },
  60431. set: function (newPosition) {
  60432. this.setPosition(newPosition);
  60433. },
  60434. enumerable: true,
  60435. configurable: true
  60436. });
  60437. Object.defineProperty(Bone.prototype, "rotation", {
  60438. get: function () {
  60439. return this.getRotation();
  60440. },
  60441. set: function (newRotation) {
  60442. this.setRotation(newRotation);
  60443. },
  60444. enumerable: true,
  60445. configurable: true
  60446. });
  60447. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60448. get: function () {
  60449. return this.getRotationQuaternion();
  60450. },
  60451. set: function (newRotation) {
  60452. this.setRotationQuaternion(newRotation);
  60453. },
  60454. enumerable: true,
  60455. configurable: true
  60456. });
  60457. Object.defineProperty(Bone.prototype, "scaling", {
  60458. get: function () {
  60459. return this.getScale();
  60460. },
  60461. set: function (newScaling) {
  60462. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60463. },
  60464. enumerable: true,
  60465. configurable: true
  60466. });
  60467. // Methods
  60468. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60469. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60470. this._baseMatrix = matrix.clone();
  60471. this._localMatrix = matrix.clone();
  60472. this._skeleton._markAsDirty();
  60473. if (updateDifferenceMatrix) {
  60474. this._updateDifferenceMatrix();
  60475. }
  60476. };
  60477. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60478. if (!rootMatrix) {
  60479. rootMatrix = this._baseMatrix;
  60480. }
  60481. if (this._parent) {
  60482. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60483. }
  60484. else {
  60485. this._absoluteTransform.copyFrom(rootMatrix);
  60486. }
  60487. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60488. for (var index = 0; index < this.children.length; index++) {
  60489. this.children[index]._updateDifferenceMatrix();
  60490. }
  60491. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60492. };
  60493. Bone.prototype.markAsDirty = function () {
  60494. this._currentRenderId++;
  60495. this._skeleton._markAsDirty();
  60496. };
  60497. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60498. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60499. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60500. // all animation may be coming from a library skeleton, so may need to create animation
  60501. if (this.animations.length === 0) {
  60502. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60503. this.animations[0].setKeys([]);
  60504. }
  60505. // get animation info / verify there is such a range from the source bone
  60506. var sourceRange = source.animations[0].getRange(rangeName);
  60507. if (!sourceRange) {
  60508. return false;
  60509. }
  60510. var from = sourceRange.from;
  60511. var to = sourceRange.to;
  60512. var sourceKeys = source.animations[0].getKeys();
  60513. // rescaling prep
  60514. var sourceBoneLength = source.length;
  60515. var sourceParent = source.getParent();
  60516. var parent = this.getParent();
  60517. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60518. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60519. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60520. var destKeys = this.animations[0].getKeys();
  60521. // loop vars declaration
  60522. var orig;
  60523. var origTranslation;
  60524. var mat;
  60525. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60526. orig = sourceKeys[key];
  60527. if (orig.frame >= from && orig.frame <= to) {
  60528. if (rescaleAsRequired) {
  60529. mat = orig.value.clone();
  60530. // scale based on parent ratio, when bone has parent
  60531. if (parentScalingReqd) {
  60532. origTranslation = mat.getTranslation();
  60533. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60534. // scale based on skeleton dimension ratio when root bone, and value is passed
  60535. }
  60536. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60537. origTranslation = mat.getTranslation();
  60538. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60539. // use original when root bone, and no data for skelDimensionsRatio
  60540. }
  60541. else {
  60542. mat = orig.value;
  60543. }
  60544. }
  60545. else {
  60546. mat = orig.value;
  60547. }
  60548. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60549. }
  60550. }
  60551. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60552. return true;
  60553. };
  60554. /**
  60555. * Translate the bone in local or world space.
  60556. * @param vec The amount to translate the bone.
  60557. * @param space The space that the translation is in.
  60558. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60559. */
  60560. Bone.prototype.translate = function (vec, space, mesh) {
  60561. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60562. var lm = this.getLocalMatrix();
  60563. if (space == BABYLON.Space.LOCAL) {
  60564. lm.m[12] += vec.x;
  60565. lm.m[13] += vec.y;
  60566. lm.m[14] += vec.z;
  60567. }
  60568. else {
  60569. var wm = null;
  60570. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60571. if (mesh) {
  60572. wm = mesh.getWorldMatrix();
  60573. }
  60574. this._skeleton.computeAbsoluteTransforms();
  60575. var tmat = Bone._tmpMats[0];
  60576. var tvec = Bone._tmpVecs[0];
  60577. if (this._parent) {
  60578. if (mesh && wm) {
  60579. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60580. tmat.multiplyToRef(wm, tmat);
  60581. }
  60582. else {
  60583. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60584. }
  60585. }
  60586. tmat.m[12] = 0;
  60587. tmat.m[13] = 0;
  60588. tmat.m[14] = 0;
  60589. tmat.invert();
  60590. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60591. lm.m[12] += tvec.x;
  60592. lm.m[13] += tvec.y;
  60593. lm.m[14] += tvec.z;
  60594. }
  60595. this.markAsDirty();
  60596. };
  60597. /**
  60598. * Set the postion of the bone in local or world space.
  60599. * @param position The position to set the bone.
  60600. * @param space The space that the position is in.
  60601. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60602. */
  60603. Bone.prototype.setPosition = function (position, space, mesh) {
  60604. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60605. var lm = this.getLocalMatrix();
  60606. if (space == BABYLON.Space.LOCAL) {
  60607. lm.m[12] = position.x;
  60608. lm.m[13] = position.y;
  60609. lm.m[14] = position.z;
  60610. }
  60611. else {
  60612. var wm = null;
  60613. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60614. if (mesh) {
  60615. wm = mesh.getWorldMatrix();
  60616. }
  60617. this._skeleton.computeAbsoluteTransforms();
  60618. var tmat = Bone._tmpMats[0];
  60619. var vec = Bone._tmpVecs[0];
  60620. if (this._parent) {
  60621. if (mesh && wm) {
  60622. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60623. tmat.multiplyToRef(wm, tmat);
  60624. }
  60625. else {
  60626. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60627. }
  60628. }
  60629. tmat.invert();
  60630. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60631. lm.m[12] = vec.x;
  60632. lm.m[13] = vec.y;
  60633. lm.m[14] = vec.z;
  60634. }
  60635. this.markAsDirty();
  60636. };
  60637. /**
  60638. * Set the absolute postion of the bone (world space).
  60639. * @param position The position to set the bone.
  60640. * @param mesh The mesh that this bone is attached to.
  60641. */
  60642. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60643. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60644. };
  60645. /**
  60646. * Set the scale of the bone on the x, y and z axes.
  60647. * @param x The scale of the bone on the x axis.
  60648. * @param x The scale of the bone on the y axis.
  60649. * @param z The scale of the bone on the z axis.
  60650. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60651. */
  60652. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60653. if (scaleChildren === void 0) { scaleChildren = false; }
  60654. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60655. if (!scaleChildren) {
  60656. this._negateScaleChildren.x = 1 / x;
  60657. this._negateScaleChildren.y = 1 / y;
  60658. this._negateScaleChildren.z = 1 / z;
  60659. }
  60660. this._syncScaleVector();
  60661. }
  60662. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60663. };
  60664. /**
  60665. * Scale the bone on the x, y and z axes.
  60666. * @param x The amount to scale the bone on the x axis.
  60667. * @param x The amount to scale the bone on the y axis.
  60668. * @param z The amount to scale the bone on the z axis.
  60669. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60670. */
  60671. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60672. if (scaleChildren === void 0) { scaleChildren = false; }
  60673. var locMat = this.getLocalMatrix();
  60674. var origLocMat = Bone._tmpMats[0];
  60675. origLocMat.copyFrom(locMat);
  60676. var origLocMatInv = Bone._tmpMats[1];
  60677. origLocMatInv.copyFrom(origLocMat);
  60678. origLocMatInv.invert();
  60679. var scaleMat = Bone._tmpMats[2];
  60680. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60681. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60682. this._scaleVector.x *= x;
  60683. this._scaleVector.y *= y;
  60684. this._scaleVector.z *= z;
  60685. locMat.multiplyToRef(origLocMatInv, locMat);
  60686. locMat.multiplyToRef(scaleMat, locMat);
  60687. locMat.multiplyToRef(origLocMat, locMat);
  60688. var parent = this.getParent();
  60689. if (parent) {
  60690. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60691. }
  60692. else {
  60693. this.getAbsoluteTransform().copyFrom(locMat);
  60694. }
  60695. var len = this.children.length;
  60696. scaleMat.invert();
  60697. for (var i = 0; i < len; i++) {
  60698. var child = this.children[i];
  60699. var cm = child.getLocalMatrix();
  60700. cm.multiplyToRef(scaleMat, cm);
  60701. var lm = child.getLocalMatrix();
  60702. lm.m[12] *= x;
  60703. lm.m[13] *= y;
  60704. lm.m[14] *= z;
  60705. }
  60706. this.computeAbsoluteTransforms();
  60707. if (scaleChildren) {
  60708. for (var i = 0; i < len; i++) {
  60709. this.children[i].scale(x, y, z, scaleChildren);
  60710. }
  60711. }
  60712. this.markAsDirty();
  60713. };
  60714. /**
  60715. * Set the yaw, pitch, and roll of the bone in local or world space.
  60716. * @param yaw The rotation of the bone on the y axis.
  60717. * @param pitch The rotation of the bone on the x axis.
  60718. * @param roll The rotation of the bone on the z axis.
  60719. * @param space The space that the axes of rotation are in.
  60720. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60721. */
  60722. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60724. var rotMat = Bone._tmpMats[0];
  60725. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60726. var rotMatInv = Bone._tmpMats[1];
  60727. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60728. rotMatInv.multiplyToRef(rotMat, rotMat);
  60729. this._rotateWithMatrix(rotMat, space, mesh);
  60730. };
  60731. /**
  60732. * Rotate the bone on an axis in local or world space.
  60733. * @param axis The axis to rotate the bone on.
  60734. * @param amount The amount to rotate the bone.
  60735. * @param space The space that the axis is in.
  60736. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60737. */
  60738. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60740. var rmat = Bone._tmpMats[0];
  60741. rmat.m[12] = 0;
  60742. rmat.m[13] = 0;
  60743. rmat.m[14] = 0;
  60744. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60745. this._rotateWithMatrix(rmat, space, mesh);
  60746. };
  60747. /**
  60748. * Set the rotation of the bone to a particular axis angle in local or world space.
  60749. * @param axis The axis to rotate the bone on.
  60750. * @param angle The angle that the bone should be rotated to.
  60751. * @param space The space that the axis is in.
  60752. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60753. */
  60754. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60755. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60756. var rotMat = Bone._tmpMats[0];
  60757. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60758. var rotMatInv = Bone._tmpMats[1];
  60759. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60760. rotMatInv.multiplyToRef(rotMat, rotMat);
  60761. this._rotateWithMatrix(rotMat, space, mesh);
  60762. };
  60763. /**
  60764. * Set the euler rotation of the bone in local of world space.
  60765. * @param rotation The euler rotation that the bone should be set to.
  60766. * @param space The space that the rotation is in.
  60767. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60768. */
  60769. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60770. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60771. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60772. };
  60773. /**
  60774. * Set the quaternion rotation of the bone in local of world space.
  60775. * @param quat The quaternion rotation that the bone should be set to.
  60776. * @param space The space that the rotation is in.
  60777. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60778. */
  60779. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60781. var rotMatInv = Bone._tmpMats[0];
  60782. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60783. var rotMat = Bone._tmpMats[1];
  60784. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60785. rotMatInv.multiplyToRef(rotMat, rotMat);
  60786. this._rotateWithMatrix(rotMat, space, mesh);
  60787. };
  60788. /**
  60789. * Set the rotation matrix of the bone in local of world space.
  60790. * @param rotMat The rotation matrix that the bone should be set to.
  60791. * @param space The space that the rotation is in.
  60792. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60793. */
  60794. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60795. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60796. var rotMatInv = Bone._tmpMats[0];
  60797. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60798. var rotMat2 = Bone._tmpMats[1];
  60799. rotMat2.copyFrom(rotMat);
  60800. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60801. this._rotateWithMatrix(rotMat2, space, mesh);
  60802. };
  60803. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60804. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60805. var lmat = this.getLocalMatrix();
  60806. var lx = lmat.m[12];
  60807. var ly = lmat.m[13];
  60808. var lz = lmat.m[14];
  60809. var parent = this.getParent();
  60810. var parentScale = Bone._tmpMats[3];
  60811. var parentScaleInv = Bone._tmpMats[4];
  60812. if (parent) {
  60813. if (space == BABYLON.Space.WORLD) {
  60814. if (mesh) {
  60815. parentScale.copyFrom(mesh.getWorldMatrix());
  60816. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60817. }
  60818. else {
  60819. parentScale.copyFrom(parent.getAbsoluteTransform());
  60820. }
  60821. }
  60822. else {
  60823. parentScale = parent._scaleMatrix;
  60824. }
  60825. parentScaleInv.copyFrom(parentScale);
  60826. parentScaleInv.invert();
  60827. lmat.multiplyToRef(parentScale, lmat);
  60828. lmat.multiplyToRef(rmat, lmat);
  60829. lmat.multiplyToRef(parentScaleInv, lmat);
  60830. }
  60831. else {
  60832. if (space == BABYLON.Space.WORLD && mesh) {
  60833. parentScale.copyFrom(mesh.getWorldMatrix());
  60834. parentScaleInv.copyFrom(parentScale);
  60835. parentScaleInv.invert();
  60836. lmat.multiplyToRef(parentScale, lmat);
  60837. lmat.multiplyToRef(rmat, lmat);
  60838. lmat.multiplyToRef(parentScaleInv, lmat);
  60839. }
  60840. else {
  60841. lmat.multiplyToRef(rmat, lmat);
  60842. }
  60843. }
  60844. lmat.m[12] = lx;
  60845. lmat.m[13] = ly;
  60846. lmat.m[14] = lz;
  60847. this.computeAbsoluteTransforms();
  60848. this.markAsDirty();
  60849. };
  60850. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60851. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60852. if (space == BABYLON.Space.WORLD) {
  60853. var scaleMatrix = Bone._tmpMats[2];
  60854. scaleMatrix.copyFrom(this._scaleMatrix);
  60855. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60856. if (mesh) {
  60857. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60858. var meshScale = Bone._tmpMats[3];
  60859. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60860. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60861. }
  60862. rotMatInv.invert();
  60863. scaleMatrix.m[0] *= this._scalingDeterminant;
  60864. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60865. }
  60866. else {
  60867. rotMatInv.copyFrom(this.getLocalMatrix());
  60868. rotMatInv.invert();
  60869. var scaleMatrix = Bone._tmpMats[2];
  60870. scaleMatrix.copyFrom(this._scaleMatrix);
  60871. if (this._parent) {
  60872. var pscaleMatrix = Bone._tmpMats[3];
  60873. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60874. pscaleMatrix.invert();
  60875. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60876. }
  60877. else {
  60878. scaleMatrix.m[0] *= this._scalingDeterminant;
  60879. }
  60880. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60881. }
  60882. };
  60883. /**
  60884. * Get the scale of the bone
  60885. * @returns the scale of the bone
  60886. */
  60887. Bone.prototype.getScale = function () {
  60888. return this._scaleVector.clone();
  60889. };
  60890. /**
  60891. * Copy the scale of the bone to a vector3.
  60892. * @param result The vector3 to copy the scale to
  60893. */
  60894. Bone.prototype.getScaleToRef = function (result) {
  60895. result.copyFrom(this._scaleVector);
  60896. };
  60897. /**
  60898. * Get the position of the bone in local or world space.
  60899. * @param space The space that the returned position is in.
  60900. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60901. * @returns The position of the bone
  60902. */
  60903. Bone.prototype.getPosition = function (space, mesh) {
  60904. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60905. if (mesh === void 0) { mesh = null; }
  60906. var pos = BABYLON.Vector3.Zero();
  60907. this.getPositionToRef(space, mesh, pos);
  60908. return pos;
  60909. };
  60910. /**
  60911. * Copy the position of the bone to a vector3 in local or world space.
  60912. * @param space The space that the returned position is in.
  60913. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60914. * @param result The vector3 to copy the position to.
  60915. */
  60916. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60918. if (space == BABYLON.Space.LOCAL) {
  60919. var lm = this.getLocalMatrix();
  60920. result.x = lm.m[12];
  60921. result.y = lm.m[13];
  60922. result.z = lm.m[14];
  60923. }
  60924. else {
  60925. var wm = null;
  60926. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60927. if (mesh) {
  60928. wm = mesh.getWorldMatrix();
  60929. }
  60930. this._skeleton.computeAbsoluteTransforms();
  60931. var tmat = Bone._tmpMats[0];
  60932. if (mesh && wm) {
  60933. tmat.copyFrom(this.getAbsoluteTransform());
  60934. tmat.multiplyToRef(wm, tmat);
  60935. }
  60936. else {
  60937. tmat = this.getAbsoluteTransform();
  60938. }
  60939. result.x = tmat.m[12];
  60940. result.y = tmat.m[13];
  60941. result.z = tmat.m[14];
  60942. }
  60943. };
  60944. /**
  60945. * Get the absolute position of the bone (world space).
  60946. * @param mesh The mesh that this bone is attached to.
  60947. * @returns The absolute position of the bone
  60948. */
  60949. Bone.prototype.getAbsolutePosition = function (mesh) {
  60950. if (mesh === void 0) { mesh = null; }
  60951. var pos = BABYLON.Vector3.Zero();
  60952. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60953. return pos;
  60954. };
  60955. /**
  60956. * Copy the absolute position of the bone (world space) to the result param.
  60957. * @param mesh The mesh that this bone is attached to.
  60958. * @param result The vector3 to copy the absolute position to.
  60959. */
  60960. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60961. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60962. };
  60963. /**
  60964. * Compute the absolute transforms of this bone and its children.
  60965. */
  60966. Bone.prototype.computeAbsoluteTransforms = function () {
  60967. if (this._parent) {
  60968. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60969. }
  60970. else {
  60971. this._absoluteTransform.copyFrom(this._localMatrix);
  60972. var poseMatrix = this._skeleton.getPoseMatrix();
  60973. if (poseMatrix) {
  60974. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60975. }
  60976. }
  60977. var children = this.children;
  60978. var len = children.length;
  60979. for (var i = 0; i < len; i++) {
  60980. children[i].computeAbsoluteTransforms();
  60981. }
  60982. };
  60983. Bone.prototype._syncScaleVector = function () {
  60984. var lm = this.getLocalMatrix();
  60985. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60986. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60987. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60988. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60989. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60990. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60991. this._scaleVector.x = xs * Math.sqrt(xsq);
  60992. this._scaleVector.y = ys * Math.sqrt(ysq);
  60993. this._scaleVector.z = zs * Math.sqrt(zsq);
  60994. if (this._parent) {
  60995. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60996. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60997. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60998. }
  60999. 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);
  61000. };
  61001. /**
  61002. * Get the world direction from an axis that is in the local space of the bone.
  61003. * @param localAxis The local direction that is used to compute the world direction.
  61004. * @param mesh The mesh that this bone is attached to.
  61005. * @returns The world direction
  61006. */
  61007. Bone.prototype.getDirection = function (localAxis, mesh) {
  61008. if (mesh === void 0) { mesh = null; }
  61009. var result = BABYLON.Vector3.Zero();
  61010. this.getDirectionToRef(localAxis, mesh, result);
  61011. return result;
  61012. };
  61013. /**
  61014. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61015. * @param localAxis The local direction that is used to compute the world direction.
  61016. * @param mesh The mesh that this bone is attached to.
  61017. * @param result The vector3 that the world direction will be copied to.
  61018. */
  61019. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61020. if (mesh === void 0) { mesh = null; }
  61021. var wm = null;
  61022. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61023. if (mesh) {
  61024. wm = mesh.getWorldMatrix();
  61025. }
  61026. this._skeleton.computeAbsoluteTransforms();
  61027. var mat = Bone._tmpMats[0];
  61028. mat.copyFrom(this.getAbsoluteTransform());
  61029. if (mesh && wm) {
  61030. mat.multiplyToRef(wm, mat);
  61031. }
  61032. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61033. result.normalize();
  61034. };
  61035. /**
  61036. * Get the euler rotation of the bone in local or world space.
  61037. * @param space The space that the rotation should be in.
  61038. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61039. * @returns The euler rotation
  61040. */
  61041. Bone.prototype.getRotation = function (space, mesh) {
  61042. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61043. if (mesh === void 0) { mesh = null; }
  61044. var result = BABYLON.Vector3.Zero();
  61045. this.getRotationToRef(space, mesh, result);
  61046. return result;
  61047. };
  61048. /**
  61049. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61050. * @param space The space that the rotation should be in.
  61051. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61052. * @param result The vector3 that the rotation should be copied to.
  61053. */
  61054. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61056. if (mesh === void 0) { mesh = null; }
  61057. var quat = Bone._tmpQuat;
  61058. this.getRotationQuaternionToRef(space, mesh, quat);
  61059. quat.toEulerAnglesToRef(result);
  61060. };
  61061. /**
  61062. * Get the quaternion rotation of the bone in either local or world space.
  61063. * @param space The space that the rotation should be in.
  61064. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61065. * @returns The quaternion rotation
  61066. */
  61067. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61068. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61069. if (mesh === void 0) { mesh = null; }
  61070. var result = BABYLON.Quaternion.Identity();
  61071. this.getRotationQuaternionToRef(space, mesh, result);
  61072. return result;
  61073. };
  61074. /**
  61075. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61076. * @param space The space that the rotation should be in.
  61077. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61078. * @param result The quaternion that the rotation should be copied to.
  61079. */
  61080. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61082. if (mesh === void 0) { mesh = null; }
  61083. if (space == BABYLON.Space.LOCAL) {
  61084. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61085. }
  61086. else {
  61087. var mat = Bone._tmpMats[0];
  61088. var amat = this.getAbsoluteTransform();
  61089. if (mesh) {
  61090. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61091. }
  61092. else {
  61093. mat.copyFrom(amat);
  61094. }
  61095. mat.m[0] *= this._scalingDeterminant;
  61096. mat.m[1] *= this._scalingDeterminant;
  61097. mat.m[2] *= this._scalingDeterminant;
  61098. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61099. }
  61100. };
  61101. /**
  61102. * Get the rotation matrix of the bone in local or world space.
  61103. * @param space The space that the rotation should be in.
  61104. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61105. * @returns The rotation matrix
  61106. */
  61107. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61109. var result = BABYLON.Matrix.Identity();
  61110. this.getRotationMatrixToRef(space, mesh, result);
  61111. return result;
  61112. };
  61113. /**
  61114. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61115. * @param space The space that the rotation should be in.
  61116. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61117. * @param result The quaternion that the rotation should be copied to.
  61118. */
  61119. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61120. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61121. if (space == BABYLON.Space.LOCAL) {
  61122. this.getLocalMatrix().getRotationMatrixToRef(result);
  61123. }
  61124. else {
  61125. var mat = Bone._tmpMats[0];
  61126. var amat = this.getAbsoluteTransform();
  61127. if (mesh) {
  61128. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61129. }
  61130. else {
  61131. mat.copyFrom(amat);
  61132. }
  61133. mat.m[0] *= this._scalingDeterminant;
  61134. mat.m[1] *= this._scalingDeterminant;
  61135. mat.m[2] *= this._scalingDeterminant;
  61136. mat.getRotationMatrixToRef(result);
  61137. }
  61138. };
  61139. /**
  61140. * Get the world position of a point that is in the local space of the bone.
  61141. * @param position The local position
  61142. * @param mesh The mesh that this bone is attached to.
  61143. * @returns The world position
  61144. */
  61145. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61146. if (mesh === void 0) { mesh = null; }
  61147. var result = BABYLON.Vector3.Zero();
  61148. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61149. return result;
  61150. };
  61151. /**
  61152. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61153. * @param position The local position
  61154. * @param mesh The mesh that this bone is attached to.
  61155. * @param result The vector3 that the world position should be copied to.
  61156. */
  61157. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61158. if (mesh === void 0) { mesh = null; }
  61159. var wm = null;
  61160. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61161. if (mesh) {
  61162. wm = mesh.getWorldMatrix();
  61163. }
  61164. this._skeleton.computeAbsoluteTransforms();
  61165. var tmat = Bone._tmpMats[0];
  61166. if (mesh && wm) {
  61167. tmat.copyFrom(this.getAbsoluteTransform());
  61168. tmat.multiplyToRef(wm, tmat);
  61169. }
  61170. else {
  61171. tmat = this.getAbsoluteTransform();
  61172. }
  61173. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61174. };
  61175. /**
  61176. * Get the local position of a point that is in world space.
  61177. * @param position The world position
  61178. * @param mesh The mesh that this bone is attached to.
  61179. * @returns The local position
  61180. */
  61181. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61182. if (mesh === void 0) { mesh = null; }
  61183. var result = BABYLON.Vector3.Zero();
  61184. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61185. return result;
  61186. };
  61187. /**
  61188. * Get the local position of a point that is in world space and copy it to the result param.
  61189. * @param position The world position
  61190. * @param mesh The mesh that this bone is attached to.
  61191. * @param result The vector3 that the local position should be copied to.
  61192. */
  61193. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61194. if (mesh === void 0) { mesh = null; }
  61195. var wm = null;
  61196. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61197. if (mesh) {
  61198. wm = mesh.getWorldMatrix();
  61199. }
  61200. this._skeleton.computeAbsoluteTransforms();
  61201. var tmat = Bone._tmpMats[0];
  61202. tmat.copyFrom(this.getAbsoluteTransform());
  61203. if (mesh && wm) {
  61204. tmat.multiplyToRef(wm, tmat);
  61205. }
  61206. tmat.invert();
  61207. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61208. };
  61209. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61210. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61211. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61212. return Bone;
  61213. }(BABYLON.Node));
  61214. BABYLON.Bone = Bone;
  61215. })(BABYLON || (BABYLON = {}));
  61216. //# sourceMappingURL=babylon.bone.js.map
  61217. var BABYLON;
  61218. (function (BABYLON) {
  61219. var BoneIKController = /** @class */ (function () {
  61220. function BoneIKController(mesh, bone, options) {
  61221. this.targetPosition = BABYLON.Vector3.Zero();
  61222. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61223. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61224. this.poleAngle = 0;
  61225. this.slerpAmount = 1;
  61226. this._bone1Quat = BABYLON.Quaternion.Identity();
  61227. this._bone1Mat = BABYLON.Matrix.Identity();
  61228. this._bone2Ang = Math.PI;
  61229. this._maxAngle = Math.PI;
  61230. this._rightHandedSystem = false;
  61231. this._bendAxis = BABYLON.Vector3.Right();
  61232. this._slerping = false;
  61233. this._adjustRoll = 0;
  61234. this._bone2 = bone;
  61235. this._bone1 = bone.getParent();
  61236. if (!this._bone1) {
  61237. return;
  61238. }
  61239. this.mesh = mesh;
  61240. var bonePos = bone.getPosition();
  61241. if (bone.getAbsoluteTransform().determinant() > 0) {
  61242. this._rightHandedSystem = true;
  61243. this._bendAxis.x = 0;
  61244. this._bendAxis.y = 0;
  61245. this._bendAxis.z = -1;
  61246. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61247. this._adjustRoll = Math.PI * .5;
  61248. this._bendAxis.z = 1;
  61249. }
  61250. }
  61251. if (this._bone1.length) {
  61252. var boneScale1 = this._bone1.getScale();
  61253. var boneScale2 = this._bone2.getScale();
  61254. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61255. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61256. }
  61257. else if (this._bone1.children[0]) {
  61258. mesh.computeWorldMatrix(true);
  61259. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61260. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61261. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61262. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61263. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61264. }
  61265. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61266. this.maxAngle = Math.PI;
  61267. if (options) {
  61268. if (options.targetMesh) {
  61269. this.targetMesh = options.targetMesh;
  61270. this.targetMesh.computeWorldMatrix(true);
  61271. }
  61272. if (options.poleTargetMesh) {
  61273. this.poleTargetMesh = options.poleTargetMesh;
  61274. this.poleTargetMesh.computeWorldMatrix(true);
  61275. }
  61276. else if (options.poleTargetBone) {
  61277. this.poleTargetBone = options.poleTargetBone;
  61278. }
  61279. else if (this._bone1.getParent()) {
  61280. this.poleTargetBone = this._bone1.getParent();
  61281. }
  61282. if (options.poleTargetLocalOffset) {
  61283. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61284. }
  61285. if (options.poleAngle) {
  61286. this.poleAngle = options.poleAngle;
  61287. }
  61288. if (options.bendAxis) {
  61289. this._bendAxis.copyFrom(options.bendAxis);
  61290. }
  61291. if (options.maxAngle) {
  61292. this.maxAngle = options.maxAngle;
  61293. }
  61294. if (options.slerpAmount) {
  61295. this.slerpAmount = options.slerpAmount;
  61296. }
  61297. }
  61298. }
  61299. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61300. get: function () {
  61301. return this._maxAngle;
  61302. },
  61303. set: function (value) {
  61304. this._setMaxAngle(value);
  61305. },
  61306. enumerable: true,
  61307. configurable: true
  61308. });
  61309. BoneIKController.prototype._setMaxAngle = function (ang) {
  61310. if (ang < 0) {
  61311. ang = 0;
  61312. }
  61313. if (ang > Math.PI || ang == undefined) {
  61314. ang = Math.PI;
  61315. }
  61316. this._maxAngle = ang;
  61317. var a = this._bone1Length;
  61318. var b = this._bone2Length;
  61319. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61320. };
  61321. BoneIKController.prototype.update = function () {
  61322. var bone1 = this._bone1;
  61323. if (!bone1) {
  61324. return;
  61325. }
  61326. var target = this.targetPosition;
  61327. var poleTarget = this.poleTargetPosition;
  61328. var mat1 = BoneIKController._tmpMats[0];
  61329. var mat2 = BoneIKController._tmpMats[1];
  61330. if (this.targetMesh) {
  61331. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61332. }
  61333. if (this.poleTargetBone) {
  61334. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61335. }
  61336. else if (this.poleTargetMesh) {
  61337. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61338. }
  61339. var bonePos = BoneIKController._tmpVecs[0];
  61340. var zaxis = BoneIKController._tmpVecs[1];
  61341. var xaxis = BoneIKController._tmpVecs[2];
  61342. var yaxis = BoneIKController._tmpVecs[3];
  61343. var upAxis = BoneIKController._tmpVecs[4];
  61344. var _tmpQuat = BoneIKController._tmpQuat;
  61345. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61346. poleTarget.subtractToRef(bonePos, upAxis);
  61347. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61348. upAxis.y = 1;
  61349. }
  61350. else {
  61351. upAxis.normalize();
  61352. }
  61353. target.subtractToRef(bonePos, yaxis);
  61354. yaxis.normalize();
  61355. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61356. zaxis.normalize();
  61357. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61358. xaxis.normalize();
  61359. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61360. var a = this._bone1Length;
  61361. var b = this._bone2Length;
  61362. var c = BABYLON.Vector3.Distance(bonePos, target);
  61363. if (this._maxReach > 0) {
  61364. c = Math.min(this._maxReach, c);
  61365. }
  61366. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61367. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61368. if (acosa > 1) {
  61369. acosa = 1;
  61370. }
  61371. if (acosb > 1) {
  61372. acosb = 1;
  61373. }
  61374. if (acosa < -1) {
  61375. acosa = -1;
  61376. }
  61377. if (acosb < -1) {
  61378. acosb = -1;
  61379. }
  61380. var angA = Math.acos(acosa);
  61381. var angB = Math.acos(acosb);
  61382. var angC = -angA - angB;
  61383. if (this._rightHandedSystem) {
  61384. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61385. mat2.multiplyToRef(mat1, mat1);
  61386. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61387. mat2.multiplyToRef(mat1, mat1);
  61388. }
  61389. else {
  61390. var _tmpVec = BoneIKController._tmpVecs[5];
  61391. _tmpVec.copyFrom(this._bendAxis);
  61392. _tmpVec.x *= -1;
  61393. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61394. mat2.multiplyToRef(mat1, mat1);
  61395. }
  61396. if (this.poleAngle) {
  61397. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61398. mat1.multiplyToRef(mat2, mat1);
  61399. }
  61400. if (this._bone1) {
  61401. if (this.slerpAmount < 1) {
  61402. if (!this._slerping) {
  61403. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61404. }
  61405. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61406. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61407. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61408. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61409. this._slerping = true;
  61410. }
  61411. else {
  61412. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61413. this._bone1Mat.copyFrom(mat1);
  61414. this._slerping = false;
  61415. }
  61416. }
  61417. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61418. this._bone2Ang = angC;
  61419. };
  61420. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61421. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61422. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61423. return BoneIKController;
  61424. }());
  61425. BABYLON.BoneIKController = BoneIKController;
  61426. })(BABYLON || (BABYLON = {}));
  61427. //# sourceMappingURL=babylon.boneIKController.js.map
  61428. var BABYLON;
  61429. (function (BABYLON) {
  61430. var BoneLookController = /** @class */ (function () {
  61431. /**
  61432. * Create a BoneLookController
  61433. * @param mesh the mesh that the bone belongs to
  61434. * @param bone the bone that will be looking to the target
  61435. * @param target the target Vector3 to look at
  61436. * @param settings optional settings:
  61437. * - maxYaw: the maximum angle the bone will yaw to
  61438. * - minYaw: the minimum angle the bone will yaw to
  61439. * - maxPitch: the maximum angle the bone will pitch to
  61440. * - minPitch: the minimum angle the bone will yaw to
  61441. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61442. * - upAxis: the up axis of the coordinate system
  61443. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61444. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61445. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61446. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61447. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61448. * - adjustRoll: used to make an adjustment to the roll of the bone
  61449. **/
  61450. function BoneLookController(mesh, bone, target, options) {
  61451. /**
  61452. * The up axis of the coordinate system that is used when the bone is rotated.
  61453. */
  61454. this.upAxis = BABYLON.Vector3.Up();
  61455. /**
  61456. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61457. */
  61458. this.upAxisSpace = BABYLON.Space.LOCAL;
  61459. /**
  61460. * Used to make an adjustment to the yaw of the bone.
  61461. */
  61462. this.adjustYaw = 0;
  61463. /**
  61464. * Used to make an adjustment to the pitch of the bone.
  61465. */
  61466. this.adjustPitch = 0;
  61467. /**
  61468. * Used to make an adjustment to the roll of the bone.
  61469. */
  61470. this.adjustRoll = 0;
  61471. /**
  61472. * 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).
  61473. */
  61474. this.slerpAmount = 1;
  61475. this._boneQuat = BABYLON.Quaternion.Identity();
  61476. this._slerping = false;
  61477. this._firstFrameSkipped = false;
  61478. this._fowardAxis = BABYLON.Vector3.Forward();
  61479. this.mesh = mesh;
  61480. this.bone = bone;
  61481. this.target = target;
  61482. if (options) {
  61483. if (options.adjustYaw) {
  61484. this.adjustYaw = options.adjustYaw;
  61485. }
  61486. if (options.adjustPitch) {
  61487. this.adjustPitch = options.adjustPitch;
  61488. }
  61489. if (options.adjustRoll) {
  61490. this.adjustRoll = options.adjustRoll;
  61491. }
  61492. if (options.maxYaw != null) {
  61493. this.maxYaw = options.maxYaw;
  61494. }
  61495. else {
  61496. this.maxYaw = Math.PI;
  61497. }
  61498. if (options.minYaw != null) {
  61499. this.minYaw = options.minYaw;
  61500. }
  61501. else {
  61502. this.minYaw = -Math.PI;
  61503. }
  61504. if (options.maxPitch != null) {
  61505. this.maxPitch = options.maxPitch;
  61506. }
  61507. else {
  61508. this.maxPitch = Math.PI;
  61509. }
  61510. if (options.minPitch != null) {
  61511. this.minPitch = options.minPitch;
  61512. }
  61513. else {
  61514. this.minPitch = -Math.PI;
  61515. }
  61516. if (options.slerpAmount != null) {
  61517. this.slerpAmount = options.slerpAmount;
  61518. }
  61519. if (options.upAxis != null) {
  61520. this.upAxis = options.upAxis;
  61521. }
  61522. if (options.upAxisSpace != null) {
  61523. this.upAxisSpace = options.upAxisSpace;
  61524. }
  61525. if (options.yawAxis != null || options.pitchAxis != null) {
  61526. var newYawAxis = BABYLON.Axis.Y;
  61527. var newPitchAxis = BABYLON.Axis.X;
  61528. if (options.yawAxis != null) {
  61529. newYawAxis = options.yawAxis.clone();
  61530. newYawAxis.normalize();
  61531. }
  61532. if (options.pitchAxis != null) {
  61533. newPitchAxis = options.pitchAxis.clone();
  61534. newPitchAxis.normalize();
  61535. }
  61536. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61537. this._transformYawPitch = BABYLON.Matrix.Identity();
  61538. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61539. this._transformYawPitchInv = this._transformYawPitch.clone();
  61540. this._transformYawPitch.invert();
  61541. }
  61542. }
  61543. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61544. this.upAxisSpace = BABYLON.Space.LOCAL;
  61545. }
  61546. }
  61547. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61548. /**
  61549. * Get/set the minimum yaw angle that the bone can look to.
  61550. */
  61551. get: function () {
  61552. return this._minYaw;
  61553. },
  61554. set: function (value) {
  61555. this._minYaw = value;
  61556. this._minYawSin = Math.sin(value);
  61557. this._minYawCos = Math.cos(value);
  61558. if (this._maxYaw != null) {
  61559. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61560. this._yawRange = this._maxYaw - this._minYaw;
  61561. }
  61562. },
  61563. enumerable: true,
  61564. configurable: true
  61565. });
  61566. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61567. /**
  61568. * Get/set the maximum yaw angle that the bone can look to.
  61569. */
  61570. get: function () {
  61571. return this._maxYaw;
  61572. },
  61573. set: function (value) {
  61574. this._maxYaw = value;
  61575. this._maxYawSin = Math.sin(value);
  61576. this._maxYawCos = Math.cos(value);
  61577. if (this._minYaw != null) {
  61578. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61579. this._yawRange = this._maxYaw - this._minYaw;
  61580. }
  61581. },
  61582. enumerable: true,
  61583. configurable: true
  61584. });
  61585. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61586. /**
  61587. * Get/set the minimum pitch angle that the bone can look to.
  61588. */
  61589. get: function () {
  61590. return this._minPitch;
  61591. },
  61592. set: function (value) {
  61593. this._minPitch = value;
  61594. this._minPitchTan = Math.tan(value);
  61595. },
  61596. enumerable: true,
  61597. configurable: true
  61598. });
  61599. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61600. /**
  61601. * Get/set the maximum pitch angle that the bone can look to.
  61602. */
  61603. get: function () {
  61604. return this._maxPitch;
  61605. },
  61606. set: function (value) {
  61607. this._maxPitch = value;
  61608. this._maxPitchTan = Math.tan(value);
  61609. },
  61610. enumerable: true,
  61611. configurable: true
  61612. });
  61613. /**
  61614. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61615. */
  61616. BoneLookController.prototype.update = function () {
  61617. //skip the first frame when slerping so that the mesh rotation is correct
  61618. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61619. this._firstFrameSkipped = true;
  61620. return;
  61621. }
  61622. var bone = this.bone;
  61623. var bonePos = BoneLookController._tmpVecs[0];
  61624. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61625. var target = this.target;
  61626. var _tmpMat1 = BoneLookController._tmpMats[0];
  61627. var _tmpMat2 = BoneLookController._tmpMats[1];
  61628. var mesh = this.mesh;
  61629. var parentBone = bone.getParent();
  61630. var upAxis = BoneLookController._tmpVecs[1];
  61631. upAxis.copyFrom(this.upAxis);
  61632. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61633. if (this._transformYawPitch) {
  61634. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61635. }
  61636. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61637. }
  61638. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61639. mesh.getDirectionToRef(upAxis, upAxis);
  61640. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61641. upAxis.normalize();
  61642. }
  61643. }
  61644. var checkYaw = false;
  61645. var checkPitch = false;
  61646. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61647. checkYaw = true;
  61648. }
  61649. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61650. checkPitch = true;
  61651. }
  61652. if (checkYaw || checkPitch) {
  61653. var spaceMat = BoneLookController._tmpMats[2];
  61654. var spaceMatInv = BoneLookController._tmpMats[3];
  61655. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61656. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61657. }
  61658. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61659. spaceMat.copyFrom(mesh.getWorldMatrix());
  61660. }
  61661. else {
  61662. var forwardAxis = BoneLookController._tmpVecs[2];
  61663. forwardAxis.copyFrom(this._fowardAxis);
  61664. if (this._transformYawPitch) {
  61665. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61666. }
  61667. if (parentBone) {
  61668. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61669. }
  61670. else {
  61671. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61672. }
  61673. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61674. rightAxis.normalize();
  61675. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61676. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61677. }
  61678. spaceMat.invertToRef(spaceMatInv);
  61679. var xzlen = null;
  61680. if (checkPitch) {
  61681. var localTarget = BoneLookController._tmpVecs[3];
  61682. target.subtractToRef(bonePos, localTarget);
  61683. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61684. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61685. var pitch = Math.atan2(localTarget.y, xzlen);
  61686. var newPitch = pitch;
  61687. if (pitch > this._maxPitch) {
  61688. localTarget.y = this._maxPitchTan * xzlen;
  61689. newPitch = this._maxPitch;
  61690. }
  61691. else if (pitch < this._minPitch) {
  61692. localTarget.y = this._minPitchTan * xzlen;
  61693. newPitch = this._minPitch;
  61694. }
  61695. if (pitch != newPitch) {
  61696. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61697. localTarget.addInPlace(bonePos);
  61698. target = localTarget;
  61699. }
  61700. }
  61701. if (checkYaw) {
  61702. var localTarget = BoneLookController._tmpVecs[4];
  61703. target.subtractToRef(bonePos, localTarget);
  61704. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61705. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61706. var newYaw = yaw;
  61707. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61708. if (xzlen == null) {
  61709. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61710. }
  61711. if (this._yawRange > Math.PI) {
  61712. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61713. localTarget.z = this._maxYawCos * xzlen;
  61714. localTarget.x = this._maxYawSin * xzlen;
  61715. newYaw = this._maxYaw;
  61716. }
  61717. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61718. localTarget.z = this._minYawCos * xzlen;
  61719. localTarget.x = this._minYawSin * xzlen;
  61720. newYaw = this._minYaw;
  61721. }
  61722. }
  61723. else {
  61724. if (yaw > this._maxYaw) {
  61725. localTarget.z = this._maxYawCos * xzlen;
  61726. localTarget.x = this._maxYawSin * xzlen;
  61727. newYaw = this._maxYaw;
  61728. }
  61729. else if (yaw < this._minYaw) {
  61730. localTarget.z = this._minYawCos * xzlen;
  61731. localTarget.x = this._minYawSin * xzlen;
  61732. newYaw = this._minYaw;
  61733. }
  61734. }
  61735. }
  61736. if (this._slerping && this._yawRange > Math.PI) {
  61737. //are we going to be crossing into the min/max region?
  61738. var boneFwd = BoneLookController._tmpVecs[8];
  61739. boneFwd.copyFrom(BABYLON.Axis.Z);
  61740. if (this._transformYawPitch) {
  61741. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61742. }
  61743. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61744. this._boneQuat.toRotationMatrix(boneRotMat);
  61745. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61746. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61747. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61748. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61749. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61750. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61751. if (angBtwTar > angBtwMidYaw) {
  61752. if (xzlen == null) {
  61753. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61754. }
  61755. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61756. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61757. if (angBtwMin < angBtwMax) {
  61758. newYaw = boneYaw + Math.PI * .75;
  61759. localTarget.z = Math.cos(newYaw) * xzlen;
  61760. localTarget.x = Math.sin(newYaw) * xzlen;
  61761. }
  61762. else {
  61763. newYaw = boneYaw - Math.PI * .75;
  61764. localTarget.z = Math.cos(newYaw) * xzlen;
  61765. localTarget.x = Math.sin(newYaw) * xzlen;
  61766. }
  61767. }
  61768. }
  61769. if (yaw != newYaw) {
  61770. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61771. localTarget.addInPlace(bonePos);
  61772. target = localTarget;
  61773. }
  61774. }
  61775. }
  61776. var zaxis = BoneLookController._tmpVecs[5];
  61777. var xaxis = BoneLookController._tmpVecs[6];
  61778. var yaxis = BoneLookController._tmpVecs[7];
  61779. var _tmpQuat = BoneLookController._tmpQuat;
  61780. target.subtractToRef(bonePos, zaxis);
  61781. zaxis.normalize();
  61782. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61783. xaxis.normalize();
  61784. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61785. yaxis.normalize();
  61786. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61787. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61788. return;
  61789. }
  61790. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61791. return;
  61792. }
  61793. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61794. return;
  61795. }
  61796. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61797. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61798. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61799. }
  61800. if (this.slerpAmount < 1) {
  61801. if (!this._slerping) {
  61802. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61803. }
  61804. if (this._transformYawPitch) {
  61805. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61806. }
  61807. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61808. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61809. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61810. this._slerping = true;
  61811. }
  61812. else {
  61813. if (this._transformYawPitch) {
  61814. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61815. }
  61816. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61817. this._slerping = false;
  61818. }
  61819. };
  61820. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61821. var angDiff = ang2 - ang1;
  61822. angDiff %= Math.PI * 2;
  61823. if (angDiff > Math.PI) {
  61824. angDiff -= Math.PI * 2;
  61825. }
  61826. else if (angDiff < -Math.PI) {
  61827. angDiff += Math.PI * 2;
  61828. }
  61829. return angDiff;
  61830. };
  61831. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61832. ang1 %= (2 * Math.PI);
  61833. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61834. ang2 %= (2 * Math.PI);
  61835. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61836. var ab = 0;
  61837. if (ang1 < ang2) {
  61838. ab = ang2 - ang1;
  61839. }
  61840. else {
  61841. ab = ang1 - ang2;
  61842. }
  61843. if (ab > Math.PI) {
  61844. ab = Math.PI * 2 - ab;
  61845. }
  61846. return ab;
  61847. };
  61848. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61849. ang %= (2 * Math.PI);
  61850. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61851. ang1 %= (2 * Math.PI);
  61852. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61853. ang2 %= (2 * Math.PI);
  61854. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61855. if (ang1 < ang2) {
  61856. if (ang > ang1 && ang < ang2) {
  61857. return true;
  61858. }
  61859. }
  61860. else {
  61861. if (ang > ang2 && ang < ang1) {
  61862. return true;
  61863. }
  61864. }
  61865. return false;
  61866. };
  61867. 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()];
  61868. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61869. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61870. return BoneLookController;
  61871. }());
  61872. BABYLON.BoneLookController = BoneLookController;
  61873. })(BABYLON || (BABYLON = {}));
  61874. //# sourceMappingURL=babylon.boneLookController.js.map
  61875. var BABYLON;
  61876. (function (BABYLON) {
  61877. var Skeleton = /** @class */ (function () {
  61878. function Skeleton(name, id, scene) {
  61879. this.name = name;
  61880. this.id = id;
  61881. this.bones = new Array();
  61882. this.needInitialSkinMatrix = false;
  61883. this._isDirty = true;
  61884. this._meshesWithPoseMatrix = new Array();
  61885. this._identity = BABYLON.Matrix.Identity();
  61886. this._ranges = {};
  61887. this._lastAbsoluteTransformsUpdateId = -1;
  61888. // Events
  61889. /**
  61890. * An event triggered before computing the skeleton's matrices
  61891. * @type {BABYLON.Observable}
  61892. */
  61893. this.onBeforeComputeObservable = new BABYLON.Observable();
  61894. this.bones = [];
  61895. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61896. scene.skeletons.push(this);
  61897. //make sure it will recalculate the matrix next time prepare is called.
  61898. this._isDirty = true;
  61899. }
  61900. // Members
  61901. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61902. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61903. return mesh._bonesTransformMatrices;
  61904. }
  61905. if (!this._transformMatrices) {
  61906. this.prepare();
  61907. }
  61908. return this._transformMatrices;
  61909. };
  61910. Skeleton.prototype.getScene = function () {
  61911. return this._scene;
  61912. };
  61913. // Methods
  61914. /**
  61915. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61916. */
  61917. Skeleton.prototype.toString = function (fullDetails) {
  61918. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61919. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61920. if (fullDetails) {
  61921. ret += ", Ranges: {";
  61922. var first = true;
  61923. for (var name_1 in this._ranges) {
  61924. if (first) {
  61925. ret += ", ";
  61926. first = false;
  61927. }
  61928. ret += name_1;
  61929. }
  61930. ret += "}";
  61931. }
  61932. return ret;
  61933. };
  61934. /**
  61935. * Get bone's index searching by name
  61936. * @param {string} name is bone's name to search for
  61937. * @return {number} Indice of the bone. Returns -1 if not found
  61938. */
  61939. Skeleton.prototype.getBoneIndexByName = function (name) {
  61940. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61941. if (this.bones[boneIndex].name === name) {
  61942. return boneIndex;
  61943. }
  61944. }
  61945. return -1;
  61946. };
  61947. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61948. // check name not already in use
  61949. if (!this._ranges[name]) {
  61950. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61951. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61952. if (this.bones[i].animations[0]) {
  61953. this.bones[i].animations[0].createRange(name, from, to);
  61954. }
  61955. }
  61956. }
  61957. };
  61958. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61959. if (deleteFrames === void 0) { deleteFrames = true; }
  61960. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61961. if (this.bones[i].animations[0]) {
  61962. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61963. }
  61964. }
  61965. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61966. };
  61967. Skeleton.prototype.getAnimationRange = function (name) {
  61968. return this._ranges[name];
  61969. };
  61970. /**
  61971. * Returns as an Array, all AnimationRanges defined on this skeleton
  61972. */
  61973. Skeleton.prototype.getAnimationRanges = function () {
  61974. var animationRanges = [];
  61975. var name;
  61976. var i = 0;
  61977. for (name in this._ranges) {
  61978. animationRanges[i] = this._ranges[name];
  61979. i++;
  61980. }
  61981. return animationRanges;
  61982. };
  61983. /**
  61984. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61985. */
  61986. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61987. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61988. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61989. return false;
  61990. }
  61991. var ret = true;
  61992. var frameOffset = this._getHighestAnimationFrame() + 1;
  61993. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61994. var boneDict = {};
  61995. var sourceBones = source.bones;
  61996. var nBones;
  61997. var i;
  61998. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61999. boneDict[sourceBones[i].name] = sourceBones[i];
  62000. }
  62001. if (this.bones.length !== sourceBones.length) {
  62002. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62003. ret = false;
  62004. }
  62005. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62006. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62007. var boneName = this.bones[i].name;
  62008. var sourceBone = boneDict[boneName];
  62009. if (sourceBone) {
  62010. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62011. }
  62012. else {
  62013. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62014. ret = false;
  62015. }
  62016. }
  62017. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62018. var range = source.getAnimationRange(name);
  62019. if (range) {
  62020. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62021. }
  62022. return ret;
  62023. };
  62024. Skeleton.prototype.returnToRest = function () {
  62025. for (var index = 0; index < this.bones.length; index++) {
  62026. this.bones[index].returnToRest();
  62027. }
  62028. };
  62029. Skeleton.prototype._getHighestAnimationFrame = function () {
  62030. var ret = 0;
  62031. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62032. if (this.bones[i].animations[0]) {
  62033. var highest = this.bones[i].animations[0].getHighestFrame();
  62034. if (ret < highest) {
  62035. ret = highest;
  62036. }
  62037. }
  62038. }
  62039. return ret;
  62040. };
  62041. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62042. var range = this.getAnimationRange(name);
  62043. if (!range) {
  62044. return null;
  62045. }
  62046. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62047. };
  62048. Skeleton.prototype._markAsDirty = function () {
  62049. this._isDirty = true;
  62050. };
  62051. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62052. this._meshesWithPoseMatrix.push(mesh);
  62053. };
  62054. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62055. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62056. if (index > -1) {
  62057. this._meshesWithPoseMatrix.splice(index, 1);
  62058. }
  62059. };
  62060. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62061. this.onBeforeComputeObservable.notifyObservers(this);
  62062. for (var index = 0; index < this.bones.length; index++) {
  62063. var bone = this.bones[index];
  62064. var parentBone = bone.getParent();
  62065. if (parentBone) {
  62066. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62067. }
  62068. else {
  62069. if (initialSkinMatrix) {
  62070. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62071. }
  62072. else {
  62073. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62074. }
  62075. }
  62076. if (bone._index !== -1) {
  62077. var mappedIndex = bone._index === null ? index : bone._index;
  62078. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62079. }
  62080. }
  62081. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62082. };
  62083. Skeleton.prototype.prepare = function () {
  62084. if (!this._isDirty) {
  62085. return;
  62086. }
  62087. if (this.needInitialSkinMatrix) {
  62088. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62089. var mesh = this._meshesWithPoseMatrix[index];
  62090. var poseMatrix = mesh.getPoseMatrix();
  62091. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62092. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62093. }
  62094. if (this._synchronizedWithMesh !== mesh) {
  62095. this._synchronizedWithMesh = mesh;
  62096. // Prepare bones
  62097. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62098. var bone = this.bones[boneIndex];
  62099. if (!bone.getParent()) {
  62100. var matrix = bone.getBaseMatrix();
  62101. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62102. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62103. }
  62104. }
  62105. }
  62106. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62107. }
  62108. }
  62109. else {
  62110. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62111. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62112. }
  62113. this._computeTransformMatrices(this._transformMatrices, null);
  62114. }
  62115. this._isDirty = false;
  62116. this._scene._activeBones.addCount(this.bones.length, false);
  62117. };
  62118. Skeleton.prototype.getAnimatables = function () {
  62119. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62120. this._animatables = [];
  62121. for (var index = 0; index < this.bones.length; index++) {
  62122. this._animatables.push(this.bones[index]);
  62123. }
  62124. }
  62125. return this._animatables;
  62126. };
  62127. Skeleton.prototype.clone = function (name, id) {
  62128. var result = new Skeleton(name, id || name, this._scene);
  62129. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62130. for (var index = 0; index < this.bones.length; index++) {
  62131. var source = this.bones[index];
  62132. var parentBone = null;
  62133. var parent_1 = source.getParent();
  62134. if (parent_1) {
  62135. var parentIndex = this.bones.indexOf(parent_1);
  62136. parentBone = result.bones[parentIndex];
  62137. }
  62138. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62139. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62140. }
  62141. if (this._ranges) {
  62142. result._ranges = {};
  62143. for (var rangeName in this._ranges) {
  62144. var range = this._ranges[rangeName];
  62145. if (range) {
  62146. result._ranges[rangeName] = range.clone();
  62147. }
  62148. }
  62149. }
  62150. this._isDirty = true;
  62151. return result;
  62152. };
  62153. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62154. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62155. this.bones.forEach(function (bone) {
  62156. bone.animations.forEach(function (animation) {
  62157. animation.enableBlending = true;
  62158. animation.blendingSpeed = blendingSpeed;
  62159. });
  62160. });
  62161. };
  62162. Skeleton.prototype.dispose = function () {
  62163. this._meshesWithPoseMatrix = [];
  62164. // Animations
  62165. this.getScene().stopAnimation(this);
  62166. // Remove from scene
  62167. this.getScene().removeSkeleton(this);
  62168. };
  62169. Skeleton.prototype.serialize = function () {
  62170. var serializationObject = {};
  62171. serializationObject.name = this.name;
  62172. serializationObject.id = this.id;
  62173. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62174. serializationObject.bones = [];
  62175. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62176. for (var index = 0; index < this.bones.length; index++) {
  62177. var bone = this.bones[index];
  62178. var parent_2 = bone.getParent();
  62179. var serializedBone = {
  62180. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62181. name: bone.name,
  62182. matrix: bone.getBaseMatrix().toArray(),
  62183. rest: bone.getRestPose().toArray()
  62184. };
  62185. serializationObject.bones.push(serializedBone);
  62186. if (bone.length) {
  62187. serializedBone.length = bone.length;
  62188. }
  62189. if (bone.animations && bone.animations.length > 0) {
  62190. serializedBone.animation = bone.animations[0].serialize();
  62191. }
  62192. serializationObject.ranges = [];
  62193. for (var name in this._ranges) {
  62194. var source = this._ranges[name];
  62195. if (!source) {
  62196. continue;
  62197. }
  62198. var range = {};
  62199. range.name = name;
  62200. range.from = source.from;
  62201. range.to = source.to;
  62202. serializationObject.ranges.push(range);
  62203. }
  62204. }
  62205. return serializationObject;
  62206. };
  62207. Skeleton.Parse = function (parsedSkeleton, scene) {
  62208. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62209. if (parsedSkeleton.dimensionsAtRest) {
  62210. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62211. }
  62212. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62213. var index;
  62214. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62215. var parsedBone = parsedSkeleton.bones[index];
  62216. var parentBone = null;
  62217. if (parsedBone.parentBoneIndex > -1) {
  62218. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62219. }
  62220. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62221. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62222. if (parsedBone.length) {
  62223. bone.length = parsedBone.length;
  62224. }
  62225. if (parsedBone.animation) {
  62226. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62227. }
  62228. }
  62229. // placed after bones, so createAnimationRange can cascade down
  62230. if (parsedSkeleton.ranges) {
  62231. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62232. var data = parsedSkeleton.ranges[index];
  62233. skeleton.createAnimationRange(data.name, data.from, data.to);
  62234. }
  62235. }
  62236. return skeleton;
  62237. };
  62238. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62239. if (forceUpdate === void 0) { forceUpdate = false; }
  62240. var renderId = this._scene.getRenderId();
  62241. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62242. this.bones[0].computeAbsoluteTransforms();
  62243. this._lastAbsoluteTransformsUpdateId = renderId;
  62244. }
  62245. };
  62246. Skeleton.prototype.getPoseMatrix = function () {
  62247. var poseMatrix = null;
  62248. if (this._meshesWithPoseMatrix.length > 0) {
  62249. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62250. }
  62251. return poseMatrix;
  62252. };
  62253. Skeleton.prototype.sortBones = function () {
  62254. var bones = new Array();
  62255. var visited = new Array(this.bones.length);
  62256. for (var index = 0; index < this.bones.length; index++) {
  62257. this._sortBones(index, bones, visited);
  62258. }
  62259. this.bones = bones;
  62260. };
  62261. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62262. if (visited[index]) {
  62263. return;
  62264. }
  62265. visited[index] = true;
  62266. var bone = this.bones[index];
  62267. if (bone._index === undefined) {
  62268. bone._index = index;
  62269. }
  62270. var parentBone = bone.getParent();
  62271. if (parentBone) {
  62272. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62273. }
  62274. bones.push(bone);
  62275. };
  62276. return Skeleton;
  62277. }());
  62278. BABYLON.Skeleton = Skeleton;
  62279. })(BABYLON || (BABYLON = {}));
  62280. //# sourceMappingURL=babylon.skeleton.js.map
  62281. var BABYLON;
  62282. (function (BABYLON) {
  62283. var SphericalPolynomial = /** @class */ (function () {
  62284. function SphericalPolynomial() {
  62285. this.x = BABYLON.Vector3.Zero();
  62286. this.y = BABYLON.Vector3.Zero();
  62287. this.z = BABYLON.Vector3.Zero();
  62288. this.xx = BABYLON.Vector3.Zero();
  62289. this.yy = BABYLON.Vector3.Zero();
  62290. this.zz = BABYLON.Vector3.Zero();
  62291. this.xy = BABYLON.Vector3.Zero();
  62292. this.yz = BABYLON.Vector3.Zero();
  62293. this.zx = BABYLON.Vector3.Zero();
  62294. }
  62295. SphericalPolynomial.prototype.addAmbient = function (color) {
  62296. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62297. this.xx = this.xx.add(colorVector);
  62298. this.yy = this.yy.add(colorVector);
  62299. this.zz = this.zz.add(colorVector);
  62300. };
  62301. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62302. var result = new SphericalPolynomial();
  62303. result.x = harmonics.L11.scale(1.02333);
  62304. result.y = harmonics.L1_1.scale(1.02333);
  62305. result.z = harmonics.L10.scale(1.02333);
  62306. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62307. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62308. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62309. result.yz = harmonics.L2_1.scale(0.858086);
  62310. result.zx = harmonics.L21.scale(0.858086);
  62311. result.xy = harmonics.L2_2.scale(0.858086);
  62312. result.scale(1.0 / Math.PI);
  62313. return result;
  62314. };
  62315. SphericalPolynomial.prototype.scale = function (scale) {
  62316. this.x = this.x.scale(scale);
  62317. this.y = this.y.scale(scale);
  62318. this.z = this.z.scale(scale);
  62319. this.xx = this.xx.scale(scale);
  62320. this.yy = this.yy.scale(scale);
  62321. this.zz = this.zz.scale(scale);
  62322. this.yz = this.yz.scale(scale);
  62323. this.zx = this.zx.scale(scale);
  62324. this.xy = this.xy.scale(scale);
  62325. };
  62326. return SphericalPolynomial;
  62327. }());
  62328. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62329. var SphericalHarmonics = /** @class */ (function () {
  62330. function SphericalHarmonics() {
  62331. this.L00 = BABYLON.Vector3.Zero();
  62332. this.L1_1 = BABYLON.Vector3.Zero();
  62333. this.L10 = BABYLON.Vector3.Zero();
  62334. this.L11 = BABYLON.Vector3.Zero();
  62335. this.L2_2 = BABYLON.Vector3.Zero();
  62336. this.L2_1 = BABYLON.Vector3.Zero();
  62337. this.L20 = BABYLON.Vector3.Zero();
  62338. this.L21 = BABYLON.Vector3.Zero();
  62339. this.L22 = BABYLON.Vector3.Zero();
  62340. }
  62341. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62342. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62343. var c = colorVector.scale(deltaSolidAngle);
  62344. this.L00 = this.L00.add(c.scale(0.282095));
  62345. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62346. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62347. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62348. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62349. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62350. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62351. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62352. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62353. };
  62354. SphericalHarmonics.prototype.scale = function (scale) {
  62355. this.L00 = this.L00.scale(scale);
  62356. this.L1_1 = this.L1_1.scale(scale);
  62357. this.L10 = this.L10.scale(scale);
  62358. this.L11 = this.L11.scale(scale);
  62359. this.L2_2 = this.L2_2.scale(scale);
  62360. this.L2_1 = this.L2_1.scale(scale);
  62361. this.L20 = this.L20.scale(scale);
  62362. this.L21 = this.L21.scale(scale);
  62363. this.L22 = this.L22.scale(scale);
  62364. };
  62365. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62366. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62367. //
  62368. // E_lm = A_l * L_lm
  62369. //
  62370. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62371. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62372. // the scaling factors are given in equation 9.
  62373. // Constant (Band 0)
  62374. this.L00 = this.L00.scale(3.141593);
  62375. // Linear (Band 1)
  62376. this.L1_1 = this.L1_1.scale(2.094395);
  62377. this.L10 = this.L10.scale(2.094395);
  62378. this.L11 = this.L11.scale(2.094395);
  62379. // Quadratic (Band 2)
  62380. this.L2_2 = this.L2_2.scale(0.785398);
  62381. this.L2_1 = this.L2_1.scale(0.785398);
  62382. this.L20 = this.L20.scale(0.785398);
  62383. this.L21 = this.L21.scale(0.785398);
  62384. this.L22 = this.L22.scale(0.785398);
  62385. };
  62386. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62387. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62388. // L = (1/pi) * E * rho
  62389. //
  62390. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62391. this.scale(1.0 / Math.PI);
  62392. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62393. // (The pixel shader must apply albedo after texture fetches, etc).
  62394. };
  62395. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62396. var result = new SphericalHarmonics();
  62397. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62398. result.L1_1 = polynomial.y.scale(0.977204);
  62399. result.L10 = polynomial.z.scale(0.977204);
  62400. result.L11 = polynomial.x.scale(0.977204);
  62401. result.L2_2 = polynomial.xy.scale(1.16538);
  62402. result.L2_1 = polynomial.yz.scale(1.16538);
  62403. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62404. result.L21 = polynomial.zx.scale(1.16538);
  62405. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62406. result.scale(Math.PI);
  62407. return result;
  62408. };
  62409. return SphericalHarmonics;
  62410. }());
  62411. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62412. })(BABYLON || (BABYLON = {}));
  62413. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62414. var BABYLON;
  62415. (function (BABYLON) {
  62416. var Internals;
  62417. (function (Internals) {
  62418. var FileFaceOrientation = /** @class */ (function () {
  62419. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62420. this.name = name;
  62421. this.worldAxisForNormal = worldAxisForNormal;
  62422. this.worldAxisForFileX = worldAxisForFileX;
  62423. this.worldAxisForFileY = worldAxisForFileY;
  62424. }
  62425. return FileFaceOrientation;
  62426. }());
  62427. ;
  62428. /**
  62429. * Helper class dealing with the extraction of spherical polynomial dataArray
  62430. * from a cube map.
  62431. */
  62432. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62433. function CubeMapToSphericalPolynomialTools() {
  62434. }
  62435. /**
  62436. * Converts a texture to the according Spherical Polynomial data.
  62437. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62438. *
  62439. * @param texture The texture to extract the information from.
  62440. * @return The Spherical Polynomial data.
  62441. */
  62442. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62443. if (!texture.isCube) {
  62444. // Only supports cube Textures currently.
  62445. return null;
  62446. }
  62447. var size = texture.getSize().width;
  62448. var right = texture.readPixels(0);
  62449. var left = texture.readPixels(1);
  62450. var up;
  62451. var down;
  62452. if (texture.isRenderTarget) {
  62453. up = texture.readPixels(3);
  62454. down = texture.readPixels(2);
  62455. }
  62456. else {
  62457. up = texture.readPixels(2);
  62458. down = texture.readPixels(3);
  62459. }
  62460. var front = texture.readPixels(4);
  62461. var back = texture.readPixels(5);
  62462. var gammaSpace = texture.gammaSpace;
  62463. // Always read as RGBA.
  62464. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62465. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62466. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62467. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62468. }
  62469. var cubeInfo = {
  62470. size: size,
  62471. right: right,
  62472. left: left,
  62473. up: up,
  62474. down: down,
  62475. front: front,
  62476. back: back,
  62477. format: format,
  62478. type: type,
  62479. gammaSpace: gammaSpace,
  62480. };
  62481. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62482. };
  62483. /**
  62484. * Converts a cubemap to the according Spherical Polynomial data.
  62485. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62486. *
  62487. * @param cubeInfo The Cube map to extract the information from.
  62488. * @return The Spherical Polynomial data.
  62489. */
  62490. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62491. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62492. var totalSolidAngle = 0.0;
  62493. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62494. var du = 2.0 / cubeInfo.size;
  62495. var dv = du;
  62496. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62497. var minUV = du * 0.5 - 1.0;
  62498. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62499. var fileFace = this.FileFaces[faceIndex];
  62500. var dataArray = cubeInfo[fileFace.name];
  62501. var v = minUV;
  62502. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62503. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62504. // Because SP is still linear, so summation is fine in that basis.
  62505. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62506. for (var y = 0; y < cubeInfo.size; y++) {
  62507. var u = minUV;
  62508. for (var x = 0; x < cubeInfo.size; x++) {
  62509. // World direction (not normalised)
  62510. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62511. worldDirection.normalize();
  62512. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62513. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62514. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62515. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62516. // Handle Integer types.
  62517. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62518. r /= 255;
  62519. g /= 255;
  62520. b /= 255;
  62521. }
  62522. // Handle Gamma space textures.
  62523. if (cubeInfo.gammaSpace) {
  62524. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62525. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62526. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62527. }
  62528. var color = new BABYLON.Color3(r, g, b);
  62529. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62530. totalSolidAngle += deltaSolidAngle;
  62531. u += du;
  62532. }
  62533. v += dv;
  62534. }
  62535. }
  62536. // Solid angle for entire sphere is 4*pi
  62537. var sphereSolidAngle = 4.0 * Math.PI;
  62538. // Adjust the solid angle to allow for how many faces we processed.
  62539. var facesProcessed = 6.0;
  62540. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62541. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62542. // This is needed because the numerical integration over the cube uses a
  62543. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62544. // and also to compensate for accumulative error due to float precision in the summation.
  62545. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62546. sphericalHarmonics.scale(correctionFactor);
  62547. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62548. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62549. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62550. };
  62551. CubeMapToSphericalPolynomialTools.FileFaces = [
  62552. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62553. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62554. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62555. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62556. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62557. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62558. ];
  62559. return CubeMapToSphericalPolynomialTools;
  62560. }());
  62561. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62562. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62563. })(BABYLON || (BABYLON = {}));
  62564. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62565. var BABYLON;
  62566. (function (BABYLON) {
  62567. var Internals;
  62568. (function (Internals) {
  62569. /**
  62570. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62571. */
  62572. var PanoramaToCubeMapTools = /** @class */ (function () {
  62573. function PanoramaToCubeMapTools() {
  62574. }
  62575. /**
  62576. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62577. *
  62578. * @param float32Array The source data.
  62579. * @param inputWidth The width of the input panorama.
  62580. * @param inputhHeight The height of the input panorama.
  62581. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62582. * @return The cubemap data
  62583. */
  62584. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62585. if (!float32Array) {
  62586. throw "ConvertPanoramaToCubemap: input cannot be null";
  62587. }
  62588. if (float32Array.length != inputWidth * inputHeight * 3) {
  62589. throw "ConvertPanoramaToCubemap: input size is wrong";
  62590. }
  62591. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62592. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62593. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62594. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62595. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62596. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62597. return {
  62598. front: textureFront,
  62599. back: textureBack,
  62600. left: textureLeft,
  62601. right: textureRight,
  62602. up: textureUp,
  62603. down: textureDown,
  62604. size: size,
  62605. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62606. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62607. gammaSpace: false,
  62608. };
  62609. };
  62610. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62611. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62612. var textureArray = new Float32Array(buffer);
  62613. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62614. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62615. var dy = 1 / texSize;
  62616. var fy = 0;
  62617. for (var y = 0; y < texSize; y++) {
  62618. var xv1 = faceData[0];
  62619. var xv2 = faceData[2];
  62620. for (var x = 0; x < texSize; x++) {
  62621. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62622. v.normalize();
  62623. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62624. // 3 channels per pixels
  62625. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62626. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62627. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62628. xv1 = xv1.add(rotDX1);
  62629. xv2 = xv2.add(rotDX2);
  62630. }
  62631. fy += dy;
  62632. }
  62633. return textureArray;
  62634. };
  62635. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62636. var theta = Math.atan2(vDir.z, vDir.x);
  62637. var phi = Math.acos(vDir.y);
  62638. while (theta < -Math.PI)
  62639. theta += 2 * Math.PI;
  62640. while (theta > Math.PI)
  62641. theta -= 2 * Math.PI;
  62642. var dx = theta / Math.PI;
  62643. var dy = phi / Math.PI;
  62644. // recenter.
  62645. dx = dx * 0.5 + 0.5;
  62646. var px = Math.round(dx * inputWidth);
  62647. if (px < 0)
  62648. px = 0;
  62649. else if (px >= inputWidth)
  62650. px = inputWidth - 1;
  62651. var py = Math.round(dy * inputHeight);
  62652. if (py < 0)
  62653. py = 0;
  62654. else if (py >= inputHeight)
  62655. py = inputHeight - 1;
  62656. var inputY = (inputHeight - py - 1);
  62657. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62658. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62659. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62660. return {
  62661. r: r,
  62662. g: g,
  62663. b: b
  62664. };
  62665. };
  62666. PanoramaToCubeMapTools.FACE_FRONT = [
  62667. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62668. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62669. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62670. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62671. ];
  62672. PanoramaToCubeMapTools.FACE_BACK = [
  62673. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62674. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62675. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62676. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62677. ];
  62678. PanoramaToCubeMapTools.FACE_RIGHT = [
  62679. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62680. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62681. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62682. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62683. ];
  62684. PanoramaToCubeMapTools.FACE_LEFT = [
  62685. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62686. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62687. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62688. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62689. ];
  62690. PanoramaToCubeMapTools.FACE_DOWN = [
  62691. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62692. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62693. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62694. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62695. ];
  62696. PanoramaToCubeMapTools.FACE_UP = [
  62697. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62698. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62699. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62700. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62701. ];
  62702. return PanoramaToCubeMapTools;
  62703. }());
  62704. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62705. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62706. })(BABYLON || (BABYLON = {}));
  62707. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62708. var BABYLON;
  62709. (function (BABYLON) {
  62710. var Internals;
  62711. (function (Internals) {
  62712. ;
  62713. /**
  62714. * This groups tools to convert HDR texture to native colors array.
  62715. */
  62716. var HDRTools = /** @class */ (function () {
  62717. function HDRTools() {
  62718. }
  62719. HDRTools.Ldexp = function (mantissa, exponent) {
  62720. if (exponent > 1023) {
  62721. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62722. }
  62723. if (exponent < -1074) {
  62724. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62725. }
  62726. return mantissa * Math.pow(2, exponent);
  62727. };
  62728. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62729. if (exponent > 0) {
  62730. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62731. float32array[index + 0] = red * exponent;
  62732. float32array[index + 1] = green * exponent;
  62733. float32array[index + 2] = blue * exponent;
  62734. }
  62735. else {
  62736. float32array[index + 0] = 0;
  62737. float32array[index + 1] = 0;
  62738. float32array[index + 2] = 0;
  62739. }
  62740. };
  62741. HDRTools.readStringLine = function (uint8array, startIndex) {
  62742. var line = "";
  62743. var character = "";
  62744. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62745. character = String.fromCharCode(uint8array[i]);
  62746. if (character == "\n") {
  62747. break;
  62748. }
  62749. line += character;
  62750. }
  62751. return line;
  62752. };
  62753. /**
  62754. * Reads header information from an RGBE texture stored in a native array.
  62755. * More information on this format are available here:
  62756. * https://en.wikipedia.org/wiki/RGBE_image_format
  62757. *
  62758. * @param uint8array The binary file stored in native array.
  62759. * @return The header information.
  62760. */
  62761. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62762. var height = 0;
  62763. var width = 0;
  62764. var line = this.readStringLine(uint8array, 0);
  62765. if (line[0] != '#' || line[1] != '?') {
  62766. throw "Bad HDR Format.";
  62767. }
  62768. var endOfHeader = false;
  62769. var findFormat = false;
  62770. var lineIndex = 0;
  62771. do {
  62772. lineIndex += (line.length + 1);
  62773. line = this.readStringLine(uint8array, lineIndex);
  62774. if (line == "FORMAT=32-bit_rle_rgbe") {
  62775. findFormat = true;
  62776. }
  62777. else if (line.length == 0) {
  62778. endOfHeader = true;
  62779. }
  62780. } while (!endOfHeader);
  62781. if (!findFormat) {
  62782. throw "HDR Bad header format, unsupported FORMAT";
  62783. }
  62784. lineIndex += (line.length + 1);
  62785. line = this.readStringLine(uint8array, lineIndex);
  62786. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62787. var match = sizeRegexp.exec(line);
  62788. // TODO. Support +Y and -X if needed.
  62789. if (!match || match.length < 3) {
  62790. throw "HDR Bad header format, no size";
  62791. }
  62792. width = parseInt(match[2]);
  62793. height = parseInt(match[1]);
  62794. if (width < 8 || width > 0x7fff) {
  62795. throw "HDR Bad header format, unsupported size";
  62796. }
  62797. lineIndex += (line.length + 1);
  62798. return {
  62799. height: height,
  62800. width: width,
  62801. dataPosition: lineIndex
  62802. };
  62803. };
  62804. /**
  62805. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62806. * This RGBE texture needs to store the information as a panorama.
  62807. *
  62808. * More information on this format are available here:
  62809. * https://en.wikipedia.org/wiki/RGBE_image_format
  62810. *
  62811. * @param buffer The binary file stored in an array buffer.
  62812. * @param size The expected size of the extracted cubemap.
  62813. * @return The Cube Map information.
  62814. */
  62815. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62816. var uint8array = new Uint8Array(buffer);
  62817. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62818. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62819. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62820. return cubeMapData;
  62821. };
  62822. /**
  62823. * Returns the pixels data extracted from an RGBE texture.
  62824. * This pixels will be stored left to right up to down in the R G B order in one array.
  62825. *
  62826. * More information on this format are available here:
  62827. * https://en.wikipedia.org/wiki/RGBE_image_format
  62828. *
  62829. * @param uint8array The binary file stored in an array buffer.
  62830. * @param hdrInfo The header information of the file.
  62831. * @return The pixels data in RGB right to left up to down order.
  62832. */
  62833. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62834. // Keep for multi format supports.
  62835. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62836. };
  62837. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62838. var num_scanlines = hdrInfo.height;
  62839. var scanline_width = hdrInfo.width;
  62840. var a, b, c, d, count;
  62841. var dataIndex = hdrInfo.dataPosition;
  62842. var index = 0, endIndex = 0, i = 0;
  62843. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62844. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62845. // 3 channels of 4 bytes per pixel in float.
  62846. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62847. var resultArray = new Float32Array(resultBuffer);
  62848. // read in each successive scanline
  62849. while (num_scanlines > 0) {
  62850. a = uint8array[dataIndex++];
  62851. b = uint8array[dataIndex++];
  62852. c = uint8array[dataIndex++];
  62853. d = uint8array[dataIndex++];
  62854. if (a != 2 || b != 2 || (c & 0x80)) {
  62855. // this file is not run length encoded
  62856. throw "HDR Bad header format, not RLE";
  62857. }
  62858. if (((c << 8) | d) != scanline_width) {
  62859. throw "HDR Bad header format, wrong scan line width";
  62860. }
  62861. index = 0;
  62862. // read each of the four channels for the scanline into the buffer
  62863. for (i = 0; i < 4; i++) {
  62864. endIndex = (i + 1) * scanline_width;
  62865. while (index < endIndex) {
  62866. a = uint8array[dataIndex++];
  62867. b = uint8array[dataIndex++];
  62868. if (a > 128) {
  62869. // a run of the same value
  62870. count = a - 128;
  62871. if ((count == 0) || (count > endIndex - index)) {
  62872. throw "HDR Bad Format, bad scanline data (run)";
  62873. }
  62874. while (count-- > 0) {
  62875. scanLineArray[index++] = b;
  62876. }
  62877. }
  62878. else {
  62879. // a non-run
  62880. count = a;
  62881. if ((count == 0) || (count > endIndex - index)) {
  62882. throw "HDR Bad Format, bad scanline data (non-run)";
  62883. }
  62884. scanLineArray[index++] = b;
  62885. if (--count > 0) {
  62886. for (var j = 0; j < count; j++) {
  62887. scanLineArray[index++] = uint8array[dataIndex++];
  62888. }
  62889. }
  62890. }
  62891. }
  62892. }
  62893. // now convert data from buffer into floats
  62894. for (i = 0; i < scanline_width; i++) {
  62895. a = scanLineArray[i];
  62896. b = scanLineArray[i + scanline_width];
  62897. c = scanLineArray[i + 2 * scanline_width];
  62898. d = scanLineArray[i + 3 * scanline_width];
  62899. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62900. }
  62901. num_scanlines--;
  62902. }
  62903. return resultArray;
  62904. };
  62905. return HDRTools;
  62906. }());
  62907. Internals.HDRTools = HDRTools;
  62908. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62909. })(BABYLON || (BABYLON = {}));
  62910. //# sourceMappingURL=babylon.hdr.js.map
  62911. var BABYLON;
  62912. (function (BABYLON) {
  62913. /**
  62914. * This represents a texture coming from an HDR input.
  62915. *
  62916. * The only supported format is currently panorama picture stored in RGBE format.
  62917. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62918. */
  62919. var HDRCubeTexture = /** @class */ (function (_super) {
  62920. __extends(HDRCubeTexture, _super);
  62921. /**
  62922. * Instantiates an HDRTexture from the following parameters.
  62923. *
  62924. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62925. * @param scene The scene the texture will be used in
  62926. * @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.
  62927. * @param noMipmap Forces to not generate the mipmap if true
  62928. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62929. * @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)
  62930. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62931. */
  62932. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62933. if (noMipmap === void 0) { noMipmap = false; }
  62934. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62935. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62936. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62937. if (onLoad === void 0) { onLoad = null; }
  62938. if (onError === void 0) { onError = null; }
  62939. var _this = _super.call(this, scene) || this;
  62940. _this._useInGammaSpace = false;
  62941. _this._generateHarmonics = true;
  62942. _this._isBABYLONPreprocessed = false;
  62943. _this._onLoad = null;
  62944. _this._onError = null;
  62945. /**
  62946. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62947. */
  62948. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62949. /**
  62950. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62951. * This is usefull at run time to apply the good shader.
  62952. */
  62953. _this.isPMREM = false;
  62954. _this._isBlocking = true;
  62955. if (!url) {
  62956. return _this;
  62957. }
  62958. _this.name = url;
  62959. _this.url = url;
  62960. _this.hasAlpha = false;
  62961. _this.isCube = true;
  62962. _this._textureMatrix = BABYLON.Matrix.Identity();
  62963. _this._onLoad = onLoad;
  62964. _this._onError = onError;
  62965. _this.gammaSpace = false;
  62966. var caps = scene.getEngine().getCaps();
  62967. if (size) {
  62968. _this._isBABYLONPreprocessed = false;
  62969. _this._noMipmap = noMipmap;
  62970. _this._size = size;
  62971. _this._useInGammaSpace = useInGammaSpace;
  62972. _this._usePMREMGenerator = usePMREMGenerator &&
  62973. caps.textureLOD &&
  62974. caps.textureFloat &&
  62975. !_this._useInGammaSpace;
  62976. }
  62977. else {
  62978. _this._isBABYLONPreprocessed = true;
  62979. _this._noMipmap = false;
  62980. _this._useInGammaSpace = false;
  62981. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62982. !_this._useInGammaSpace;
  62983. }
  62984. _this.isPMREM = _this._usePMREMGenerator;
  62985. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62986. if (!_this._texture) {
  62987. if (!scene.useDelayedTextureLoading) {
  62988. _this.loadTexture();
  62989. }
  62990. else {
  62991. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62992. }
  62993. }
  62994. return _this;
  62995. }
  62996. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62997. /**
  62998. * Gets wether or not the texture is blocking during loading.
  62999. */
  63000. get: function () {
  63001. return this._isBlocking;
  63002. },
  63003. /**
  63004. * Sets wether or not the texture is blocking during loading.
  63005. */
  63006. set: function (value) {
  63007. this._isBlocking = value;
  63008. },
  63009. enumerable: true,
  63010. configurable: true
  63011. });
  63012. /**
  63013. * Occurs when the file is a preprocessed .babylon.hdr file.
  63014. */
  63015. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63016. var _this = this;
  63017. var mipLevels = 0;
  63018. var floatArrayView = null;
  63019. var scene = this.getScene();
  63020. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63021. var mips = new Array();
  63022. if (!floatArrayView) {
  63023. return mips;
  63024. }
  63025. var startIndex = 30;
  63026. for (var level = 0; level < mipLevels; level++) {
  63027. mips.push([]);
  63028. // Fill each pixel of the mip level.
  63029. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63030. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63031. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63032. mips[level].push(faceData);
  63033. startIndex += faceSize;
  63034. }
  63035. }
  63036. return mips;
  63037. } : null;
  63038. var callback = function (buffer) {
  63039. var scene = _this.getScene();
  63040. if (!scene) {
  63041. return null;
  63042. }
  63043. // Create Native Array Views
  63044. var intArrayView = new Int32Array(buffer);
  63045. floatArrayView = new Float32Array(buffer);
  63046. // Fill header.
  63047. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63048. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63049. // Update Texture Information.
  63050. if (!_this._texture) {
  63051. return null;
  63052. }
  63053. _this._texture.updateSize(_this._size, _this._size);
  63054. // Fill polynomial information.
  63055. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63056. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63057. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63058. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63059. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63060. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63061. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63062. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63063. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63064. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63065. _this.sphericalPolynomial = sphericalPolynomial;
  63066. // Fill pixel data.
  63067. mipLevels = intArrayView[29]; // Number of mip levels.
  63068. var startIndex = 30;
  63069. var data = [];
  63070. var faceSize = Math.pow(_this._size, 2) * 3;
  63071. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63072. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63073. startIndex += faceSize;
  63074. }
  63075. var results = [];
  63076. var byteArray = null;
  63077. // Push each faces.
  63078. for (var k = 0; k < 6; k++) {
  63079. var dataFace = null;
  63080. // To be deprecated.
  63081. if (version === 1) {
  63082. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63083. dataFace = data[j];
  63084. }
  63085. // If special cases.
  63086. if (!mipmapGenerator && dataFace) {
  63087. if (!scene.getEngine().getCaps().textureFloat) {
  63088. // 3 channels of 1 bytes per pixel in bytes.
  63089. var byteBuffer = new ArrayBuffer(faceSize);
  63090. byteArray = new Uint8Array(byteBuffer);
  63091. }
  63092. for (var i = 0; i < _this._size * _this._size; i++) {
  63093. // Put in gamma space if requested.
  63094. if (_this._useInGammaSpace) {
  63095. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63096. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63097. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63098. }
  63099. // Convert to int texture for fallback.
  63100. if (byteArray) {
  63101. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63102. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63103. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63104. // May use luminance instead if the result is not accurate.
  63105. var max = Math.max(Math.max(r, g), b);
  63106. if (max > 255) {
  63107. var scale = 255 / max;
  63108. r *= scale;
  63109. g *= scale;
  63110. b *= scale;
  63111. }
  63112. byteArray[(i * 3) + 0] = r;
  63113. byteArray[(i * 3) + 1] = g;
  63114. byteArray[(i * 3) + 2] = b;
  63115. }
  63116. }
  63117. }
  63118. // Fill the array accordingly.
  63119. if (byteArray) {
  63120. results.push(byteArray);
  63121. }
  63122. else {
  63123. results.push(dataFace);
  63124. }
  63125. }
  63126. return results;
  63127. };
  63128. if (scene) {
  63129. 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);
  63130. }
  63131. };
  63132. /**
  63133. * Occurs when the file is raw .hdr file.
  63134. */
  63135. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63136. var _this = this;
  63137. var callback = function (buffer) {
  63138. var scene = _this.getScene();
  63139. if (!scene) {
  63140. return null;
  63141. }
  63142. // Extract the raw linear data.
  63143. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63144. // Generate harmonics if needed.
  63145. if (_this._generateHarmonics) {
  63146. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63147. _this.sphericalPolynomial = sphericalPolynomial;
  63148. }
  63149. var results = [];
  63150. var byteArray = null;
  63151. // Push each faces.
  63152. for (var j = 0; j < 6; j++) {
  63153. // Create uintarray fallback.
  63154. if (!scene.getEngine().getCaps().textureFloat) {
  63155. // 3 channels of 1 bytes per pixel in bytes.
  63156. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63157. byteArray = new Uint8Array(byteBuffer);
  63158. }
  63159. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63160. // If special cases.
  63161. if (_this._useInGammaSpace || byteArray) {
  63162. for (var i = 0; i < _this._size * _this._size; i++) {
  63163. // Put in gamma space if requested.
  63164. if (_this._useInGammaSpace) {
  63165. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63166. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63167. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63168. }
  63169. // Convert to int texture for fallback.
  63170. if (byteArray) {
  63171. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63172. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63173. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63174. // May use luminance instead if the result is not accurate.
  63175. var max = Math.max(Math.max(r, g), b);
  63176. if (max > 255) {
  63177. var scale = 255 / max;
  63178. r *= scale;
  63179. g *= scale;
  63180. b *= scale;
  63181. }
  63182. byteArray[(i * 3) + 0] = r;
  63183. byteArray[(i * 3) + 1] = g;
  63184. byteArray[(i * 3) + 2] = b;
  63185. }
  63186. }
  63187. }
  63188. if (byteArray) {
  63189. results.push(byteArray);
  63190. }
  63191. else {
  63192. results.push(dataFace);
  63193. }
  63194. }
  63195. return results;
  63196. };
  63197. var mipmapGenerator = null;
  63198. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63199. // if (!this._noMipmap &&
  63200. // this._usePMREMGenerator) {
  63201. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63202. // // Custom setup of the generator matching with the PBR shader values.
  63203. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63204. // this._size,
  63205. // this._size,
  63206. // 0,
  63207. // 3,
  63208. // this.getScene().getEngine().getCaps().textureFloat,
  63209. // 2048,
  63210. // 0.25,
  63211. // false,
  63212. // true);
  63213. // return generator.filterCubeMap();
  63214. // };
  63215. // }
  63216. var scene = this.getScene();
  63217. if (scene) {
  63218. 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);
  63219. }
  63220. };
  63221. /**
  63222. * Starts the loading process of the texture.
  63223. */
  63224. HDRCubeTexture.prototype.loadTexture = function () {
  63225. if (this._isBABYLONPreprocessed) {
  63226. this.loadBabylonTexture();
  63227. }
  63228. else {
  63229. this.loadHDRTexture();
  63230. }
  63231. };
  63232. HDRCubeTexture.prototype.clone = function () {
  63233. var scene = this.getScene();
  63234. if (!scene) {
  63235. return this;
  63236. }
  63237. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63238. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63239. // Base texture
  63240. newTexture.level = this.level;
  63241. newTexture.wrapU = this.wrapU;
  63242. newTexture.wrapV = this.wrapV;
  63243. newTexture.coordinatesIndex = this.coordinatesIndex;
  63244. newTexture.coordinatesMode = this.coordinatesMode;
  63245. return newTexture;
  63246. };
  63247. // Methods
  63248. HDRCubeTexture.prototype.delayLoad = function () {
  63249. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63250. return;
  63251. }
  63252. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63253. this._texture = this._getFromCache(this.url, this._noMipmap);
  63254. if (!this._texture) {
  63255. this.loadTexture();
  63256. }
  63257. };
  63258. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63259. return this._textureMatrix;
  63260. };
  63261. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63262. this._textureMatrix = value;
  63263. };
  63264. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63265. var texture = null;
  63266. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63267. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63268. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63269. texture.name = parsedTexture.name;
  63270. texture.hasAlpha = parsedTexture.hasAlpha;
  63271. texture.level = parsedTexture.level;
  63272. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63273. texture.isBlocking = parsedTexture.isBlocking;
  63274. }
  63275. return texture;
  63276. };
  63277. HDRCubeTexture.prototype.serialize = function () {
  63278. if (!this.name) {
  63279. return null;
  63280. }
  63281. var serializationObject = {};
  63282. serializationObject.name = this.name;
  63283. serializationObject.hasAlpha = this.hasAlpha;
  63284. serializationObject.isCube = true;
  63285. serializationObject.level = this.level;
  63286. serializationObject.size = this._size;
  63287. serializationObject.coordinatesMode = this.coordinatesMode;
  63288. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63289. serializationObject.generateHarmonics = this._generateHarmonics;
  63290. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63291. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63292. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63293. serializationObject.noMipmap = this._noMipmap;
  63294. serializationObject.isBlocking = this._isBlocking;
  63295. return serializationObject;
  63296. };
  63297. /**
  63298. * Saves as a file the data contained in the texture in a binary format.
  63299. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63300. * as the spherical used in the lighting.
  63301. * @param url The HDR file url.
  63302. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63303. * @param onError Method called if any error happens during download.
  63304. * @return The packed binary data.
  63305. */
  63306. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63307. if (onError === void 0) { onError = null; }
  63308. var callback = function (buffer) {
  63309. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63310. // Returns a URL you can use as a href.
  63311. var objUrl = window.URL.createObjectURL(data);
  63312. // Simulates a link to it and click to dowload.
  63313. var a = document.createElement("a");
  63314. document.body.appendChild(a);
  63315. a.style.display = "none";
  63316. a.href = objUrl;
  63317. a.download = "envmap.babylon.hdr";
  63318. a.click();
  63319. };
  63320. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63321. };
  63322. /**
  63323. * Serializes the data contained in the texture in a binary format.
  63324. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63325. * as the spherical used in the lighting.
  63326. * @param url The HDR file url.
  63327. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63328. * @param onError Method called if any error happens during download.
  63329. * @return The packed binary data.
  63330. */
  63331. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63332. if (onError === void 0) { onError = null; }
  63333. // Needs the url tho create the texture.
  63334. if (!url) {
  63335. return;
  63336. }
  63337. // Check Power of two size.
  63338. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63339. return;
  63340. }
  63341. // Coming Back in 3.x.
  63342. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63343. };
  63344. HDRCubeTexture._facesMapping = [
  63345. "right",
  63346. "left",
  63347. "up",
  63348. "down",
  63349. "front",
  63350. "back"
  63351. ];
  63352. return HDRCubeTexture;
  63353. }(BABYLON.BaseTexture));
  63354. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63355. })(BABYLON || (BABYLON = {}));
  63356. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63357. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63358. // Huge respect for a such great lib.
  63359. // Earcut license:
  63360. // Copyright (c) 2016, Mapbox
  63361. //
  63362. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63363. // with or without fee is hereby granted, provided that the above copyright notice
  63364. // and this permission notice appear in all copies.
  63365. //
  63366. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63367. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63368. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63369. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63370. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63371. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63372. // THIS SOFTWARE.
  63373. var Earcut;
  63374. (function (Earcut) {
  63375. /**
  63376. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63377. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63378. * @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).
  63379. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63380. */
  63381. function earcut(data, holeIndices, dim) {
  63382. dim = dim || 2;
  63383. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63384. if (!outerNode)
  63385. return triangles;
  63386. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63387. if (hasHoles)
  63388. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63389. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63390. if (data.length > 80 * dim) {
  63391. minX = maxX = data[0];
  63392. minY = maxY = data[1];
  63393. for (var i = dim; i < outerLen; i += dim) {
  63394. x = data[i];
  63395. y = data[i + 1];
  63396. if (x < minX)
  63397. minX = x;
  63398. if (y < minY)
  63399. minY = y;
  63400. if (x > maxX)
  63401. maxX = x;
  63402. if (y > maxY)
  63403. maxY = y;
  63404. }
  63405. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63406. size = Math.max(maxX - minX, maxY - minY);
  63407. }
  63408. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63409. return triangles;
  63410. }
  63411. Earcut.earcut = earcut;
  63412. var Node = /** @class */ (function () {
  63413. function Node(i, x, y) {
  63414. this.i = i;
  63415. this.x = x;
  63416. this.y = y;
  63417. this.prev = null;
  63418. this.next = null;
  63419. this.z = null;
  63420. this.prevZ = null;
  63421. this.nextZ = null;
  63422. this.steiner = false;
  63423. }
  63424. return Node;
  63425. }());
  63426. // create a circular doubly linked list from polygon points in the specified winding order
  63427. function linkedList(data, start, end, dim, clockwise) {
  63428. var i, last = null;
  63429. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63430. for (i = start; i < end; i += dim)
  63431. last = insertNode(i, data[i], data[i + 1], last);
  63432. }
  63433. else {
  63434. for (i = end - dim; i >= start; i -= dim)
  63435. last = insertNode(i, data[i], data[i + 1], last);
  63436. }
  63437. if (last && equals(last, last.next)) {
  63438. removeNode(last);
  63439. last = last.next;
  63440. }
  63441. return last;
  63442. }
  63443. // eliminate colinear or duplicate points
  63444. function filterPoints(start, end) {
  63445. if (!start)
  63446. return start;
  63447. if (!end)
  63448. end = start;
  63449. var p = start, again;
  63450. do {
  63451. again = false;
  63452. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63453. removeNode(p);
  63454. p = end = p.prev;
  63455. if (p === p.next)
  63456. return undefined;
  63457. again = true;
  63458. }
  63459. else {
  63460. p = p.next;
  63461. }
  63462. } while (again || p !== end);
  63463. return end;
  63464. }
  63465. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63466. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63467. if (!ear)
  63468. return;
  63469. // interlink polygon nodes in z-order
  63470. if (!pass && size)
  63471. indexCurve(ear, minX, minY, size);
  63472. var stop = ear, prev, next;
  63473. // iterate through ears, slicing them one by one
  63474. while (ear.prev !== ear.next) {
  63475. prev = ear.prev;
  63476. next = ear.next;
  63477. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63478. // cut off the triangle
  63479. triangles.push(prev.i / dim);
  63480. triangles.push(ear.i / dim);
  63481. triangles.push(next.i / dim);
  63482. removeNode(ear);
  63483. // skipping the next vertice leads to less sliver triangles
  63484. ear = next.next;
  63485. stop = next.next;
  63486. continue;
  63487. }
  63488. ear = next;
  63489. // if we looped through the whole remaining polygon and can't find any more ears
  63490. if (ear === stop) {
  63491. // try filtering points and slicing again
  63492. if (!pass) {
  63493. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63494. // if this didn't work, try curing all small self-intersections locally
  63495. }
  63496. else if (pass === 1) {
  63497. ear = cureLocalIntersections(ear, triangles, dim);
  63498. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63499. // as a last resort, try splitting the remaining polygon into two
  63500. }
  63501. else if (pass === 2) {
  63502. splitEarcut(ear, triangles, dim, minX, minY, size);
  63503. }
  63504. break;
  63505. }
  63506. }
  63507. }
  63508. // check whether a polygon node forms a valid ear with adjacent nodes
  63509. function isEar(ear) {
  63510. var a = ear.prev, b = ear, c = ear.next;
  63511. if (area(a, b, c) >= 0)
  63512. return false; // reflex, can't be an ear
  63513. // now make sure we don't have other points inside the potential ear
  63514. var p = ear.next.next;
  63515. while (p !== ear.prev) {
  63516. if (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.next;
  63520. }
  63521. return true;
  63522. }
  63523. function isEarHashed(ear, minX, minY, size) {
  63524. var a = ear.prev, b = ear, c = ear.next;
  63525. if (area(a, b, c) >= 0)
  63526. return false; // reflex, can't be an ear
  63527. // triangle bbox; min & max are calculated like this for speed
  63528. 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);
  63529. // z-order range for the current triangle bbox;
  63530. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63531. // first look for points inside the triangle in increasing z-order
  63532. var p = ear.nextZ;
  63533. while (p && p.z <= maxZ) {
  63534. if (p !== ear.prev &&
  63535. p !== ear.next &&
  63536. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63537. area(p.prev, p, p.next) >= 0)
  63538. return false;
  63539. p = p.nextZ;
  63540. }
  63541. // then look for points in decreasing z-order
  63542. p = ear.prevZ;
  63543. while (p && p.z >= minZ) {
  63544. if (p !== ear.prev &&
  63545. p !== ear.next &&
  63546. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63547. area(p.prev, p, p.next) >= 0)
  63548. return false;
  63549. p = p.prevZ;
  63550. }
  63551. return true;
  63552. }
  63553. // go through all polygon nodes and cure small local self-intersections
  63554. function cureLocalIntersections(start, triangles, dim) {
  63555. var p = start;
  63556. do {
  63557. var a = p.prev, b = p.next.next;
  63558. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63559. triangles.push(a.i / dim);
  63560. triangles.push(p.i / dim);
  63561. triangles.push(b.i / dim);
  63562. // remove two nodes involved
  63563. removeNode(p);
  63564. removeNode(p.next);
  63565. p = start = b;
  63566. }
  63567. p = p.next;
  63568. } while (p !== start);
  63569. return p;
  63570. }
  63571. // try splitting polygon into two and triangulate them independently
  63572. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63573. // look for a valid diagonal that divides the polygon into two
  63574. var a = start;
  63575. do {
  63576. var b = a.next.next;
  63577. while (b !== a.prev) {
  63578. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63579. // split the polygon in two by the diagonal
  63580. var c = splitPolygon(a, b);
  63581. // filter colinear points around the cuts
  63582. a = filterPoints(a, a.next);
  63583. c = filterPoints(c, c.next);
  63584. // run earcut on each half
  63585. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63586. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63587. return;
  63588. }
  63589. b = b.next;
  63590. }
  63591. a = a.next;
  63592. } while (a !== start);
  63593. }
  63594. // link every hole into the outer loop, producing a single-ring polygon without holes
  63595. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63596. var queue = [], i, len, start, end, list;
  63597. for (i = 0, len = holeIndices.length; i < len; i++) {
  63598. start = holeIndices[i] * dim;
  63599. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63600. list = linkedList(data, start, end, dim, false);
  63601. if (list === list.next)
  63602. list.steiner = true;
  63603. queue.push(getLeftmost(list));
  63604. }
  63605. queue.sort(compareX);
  63606. // process holes from left to right
  63607. for (i = 0; i < queue.length; i++) {
  63608. eliminateHole(queue[i], outerNode);
  63609. outerNode = filterPoints(outerNode, outerNode.next);
  63610. }
  63611. return outerNode;
  63612. }
  63613. function compareX(a, b) {
  63614. return a.x - b.x;
  63615. }
  63616. // find a bridge between vertices that connects hole with an outer ring and and link it
  63617. function eliminateHole(hole, outerNode) {
  63618. outerNode = findHoleBridge(hole, outerNode);
  63619. if (outerNode) {
  63620. var b = splitPolygon(outerNode, hole);
  63621. filterPoints(b, b.next);
  63622. }
  63623. }
  63624. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63625. function findHoleBridge(hole, outerNode) {
  63626. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63627. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63628. // segment's endpoint with lesser x will be potential connection point
  63629. do {
  63630. if (hy <= p.y && hy >= p.next.y) {
  63631. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63632. if (x <= hx && x > qx) {
  63633. qx = x;
  63634. if (x === hx) {
  63635. if (hy === p.y)
  63636. return p;
  63637. if (hy === p.next.y)
  63638. return p.next;
  63639. }
  63640. m = p.x < p.next.x ? p : p.next;
  63641. }
  63642. }
  63643. p = p.next;
  63644. } while (p !== outerNode);
  63645. if (!m)
  63646. return null;
  63647. if (hx === qx)
  63648. return m.prev; // hole touches outer segment; pick lower endpoint
  63649. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63650. // if there are no points found, we have a valid connection;
  63651. // otherwise choose the point of the minimum angle with the ray as connection point
  63652. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63653. p = m.next;
  63654. while (p !== stop) {
  63655. if (hx >= p.x &&
  63656. p.x >= mx &&
  63657. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63658. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63659. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63660. m = p;
  63661. tanMin = tan;
  63662. }
  63663. }
  63664. p = p.next;
  63665. }
  63666. return m;
  63667. }
  63668. // interlink polygon nodes in z-order
  63669. function indexCurve(start, minX, minY, size) {
  63670. var p = start;
  63671. do {
  63672. if (p.z === null)
  63673. p.z = zOrder(p.x, p.y, minX, minY, size);
  63674. p.prevZ = p.prev;
  63675. p.nextZ = p.next;
  63676. p = p.next;
  63677. } while (p !== start);
  63678. p.prevZ.nextZ = null;
  63679. p.prevZ = null;
  63680. sortLinked(p);
  63681. }
  63682. // Simon Tatham's linked list merge sort algorithm
  63683. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63684. function sortLinked(list) {
  63685. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63686. do {
  63687. p = list;
  63688. list = null;
  63689. tail = null;
  63690. numMerges = 0;
  63691. while (p) {
  63692. numMerges++;
  63693. q = p;
  63694. pSize = 0;
  63695. for (i = 0; i < inSize; i++) {
  63696. pSize++;
  63697. q = q.nextZ;
  63698. if (!q)
  63699. break;
  63700. }
  63701. qSize = inSize;
  63702. while (pSize > 0 || (qSize > 0 && q)) {
  63703. if (pSize === 0) {
  63704. e = q;
  63705. q = q.nextZ;
  63706. qSize--;
  63707. }
  63708. else if (qSize === 0 || !q) {
  63709. e = p;
  63710. p = p.nextZ;
  63711. pSize--;
  63712. }
  63713. else if (p.z <= q.z) {
  63714. e = p;
  63715. p = p.nextZ;
  63716. pSize--;
  63717. }
  63718. else {
  63719. e = q;
  63720. q = q.nextZ;
  63721. qSize--;
  63722. }
  63723. if (tail)
  63724. tail.nextZ = e;
  63725. else
  63726. list = e;
  63727. e.prevZ = tail;
  63728. tail = e;
  63729. }
  63730. p = q;
  63731. }
  63732. tail.nextZ = null;
  63733. inSize *= 2;
  63734. } while (numMerges > 1);
  63735. return list;
  63736. }
  63737. // z-order of a point given coords and size of the data bounding box
  63738. function zOrder(x, y, minX, minY, size) {
  63739. // coords are transformed into non-negative 15-bit integer range
  63740. x = 32767 * (x - minX) / size;
  63741. y = 32767 * (y - minY) / size;
  63742. x = (x | (x << 8)) & 0x00FF00FF;
  63743. x = (x | (x << 4)) & 0x0F0F0F0F;
  63744. x = (x | (x << 2)) & 0x33333333;
  63745. x = (x | (x << 1)) & 0x55555555;
  63746. y = (y | (y << 8)) & 0x00FF00FF;
  63747. y = (y | (y << 4)) & 0x0F0F0F0F;
  63748. y = (y | (y << 2)) & 0x33333333;
  63749. y = (y | (y << 1)) & 0x55555555;
  63750. return x | (y << 1);
  63751. }
  63752. // find the leftmost node of a polygon ring
  63753. function getLeftmost(start) {
  63754. var p = start, leftmost = start;
  63755. do {
  63756. if (p.x < leftmost.x)
  63757. leftmost = p;
  63758. p = p.next;
  63759. } while (p !== start);
  63760. return leftmost;
  63761. }
  63762. // check if a point lies within a convex triangle
  63763. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63764. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63765. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63766. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63767. }
  63768. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63769. function isValidDiagonal(a, b) {
  63770. return a.next.i !== b.i &&
  63771. a.prev.i !== b.i &&
  63772. !intersectsPolygon(a, b) &&
  63773. locallyInside(a, b) &&
  63774. locallyInside(b, a) &&
  63775. middleInside(a, b);
  63776. }
  63777. // signed area of a triangle
  63778. function area(p, q, r) {
  63779. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63780. }
  63781. // check if two points are equal
  63782. function equals(p1, p2) {
  63783. return p1.x === p2.x && p1.y === p2.y;
  63784. }
  63785. // check if two segments intersect
  63786. function intersects(p1, q1, p2, q2) {
  63787. if ((equals(p1, q1) && equals(p2, q2)) ||
  63788. (equals(p1, q2) && equals(p2, q1)))
  63789. return true;
  63790. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63791. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63792. }
  63793. // check if a polygon diagonal intersects any polygon segments
  63794. function intersectsPolygon(a, b) {
  63795. var p = a;
  63796. do {
  63797. if (p.i !== a.i &&
  63798. p.next.i !== a.i &&
  63799. p.i !== b.i &&
  63800. p.next.i !== b.i &&
  63801. intersects(p, p.next, a, b))
  63802. return true;
  63803. p = p.next;
  63804. } while (p !== a);
  63805. return false;
  63806. }
  63807. // check if a polygon diagonal is locally inside the polygon
  63808. function locallyInside(a, b) {
  63809. return area(a.prev, a, a.next) < 0
  63810. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63811. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63812. }
  63813. // check if the middle point of a polygon diagonal is inside the polygon
  63814. function middleInside(a, b) {
  63815. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63816. do {
  63817. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63818. inside = !inside;
  63819. p = p.next;
  63820. } while (p !== a);
  63821. return inside;
  63822. }
  63823. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63824. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63825. function splitPolygon(a, b) {
  63826. 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;
  63827. a.next = b;
  63828. b.prev = a;
  63829. a2.next = an;
  63830. an.prev = a2;
  63831. b2.next = a2;
  63832. a2.prev = b2;
  63833. bp.next = b2;
  63834. b2.prev = bp;
  63835. return b2;
  63836. }
  63837. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63838. function insertNode(i, x, y, last) {
  63839. var p = new Node(i, x, y);
  63840. if (!last) {
  63841. p.prev = p;
  63842. p.next = p;
  63843. }
  63844. else {
  63845. p.next = last.next;
  63846. p.prev = last;
  63847. last.next.prev = p;
  63848. last.next = p;
  63849. }
  63850. return p;
  63851. }
  63852. function removeNode(p) {
  63853. p.next.prev = p.prev;
  63854. p.prev.next = p.next;
  63855. if (p.prevZ)
  63856. p.prevZ.nextZ = p.nextZ;
  63857. if (p.nextZ)
  63858. p.nextZ.prevZ = p.prevZ;
  63859. }
  63860. /**
  63861. * return a percentage difference between the polygon area and its triangulation area;
  63862. * used to verify correctness of triangulation
  63863. */
  63864. function deviation(data, holeIndices, dim, triangles) {
  63865. var hasHoles = holeIndices && holeIndices.length;
  63866. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63867. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63868. if (hasHoles) {
  63869. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63870. var start = holeIndices[i] * dim;
  63871. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63872. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63873. }
  63874. }
  63875. var trianglesArea = 0;
  63876. for (i = 0; i < triangles.length; i += 3) {
  63877. var a = triangles[i] * dim;
  63878. var b = triangles[i + 1] * dim;
  63879. var c = triangles[i + 2] * dim;
  63880. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63881. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63882. }
  63883. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63884. }
  63885. Earcut.deviation = deviation;
  63886. ;
  63887. function signedArea(data, start, end, dim) {
  63888. var sum = 0;
  63889. for (var i = start, j = end - dim; i < end; i += dim) {
  63890. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63891. j = i;
  63892. }
  63893. return sum;
  63894. }
  63895. /**
  63896. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63897. */
  63898. function flatten(data) {
  63899. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63900. for (var i = 0; i < data.length; i++) {
  63901. for (var j = 0; j < data[i].length; j++) {
  63902. for (var d = 0; d < dim; d++)
  63903. result.vertices.push(data[i][j][d]);
  63904. }
  63905. if (i > 0) {
  63906. holeIndex += data[i - 1].length;
  63907. result.holes.push(holeIndex);
  63908. }
  63909. }
  63910. return result;
  63911. }
  63912. Earcut.flatten = flatten;
  63913. ;
  63914. })(Earcut || (Earcut = {}));
  63915. //# sourceMappingURL=babylon.earcut.js.map
  63916. var BABYLON;
  63917. (function (BABYLON) {
  63918. var IndexedVector2 = /** @class */ (function (_super) {
  63919. __extends(IndexedVector2, _super);
  63920. function IndexedVector2(original, index) {
  63921. var _this = _super.call(this, original.x, original.y) || this;
  63922. _this.index = index;
  63923. return _this;
  63924. }
  63925. return IndexedVector2;
  63926. }(BABYLON.Vector2));
  63927. var PolygonPoints = /** @class */ (function () {
  63928. function PolygonPoints() {
  63929. this.elements = new Array();
  63930. }
  63931. PolygonPoints.prototype.add = function (originalPoints) {
  63932. var _this = this;
  63933. var result = new Array();
  63934. originalPoints.forEach(function (point) {
  63935. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63936. var newPoint = new IndexedVector2(point, _this.elements.length);
  63937. result.push(newPoint);
  63938. _this.elements.push(newPoint);
  63939. }
  63940. });
  63941. return result;
  63942. };
  63943. PolygonPoints.prototype.computeBounds = function () {
  63944. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63945. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63946. this.elements.forEach(function (point) {
  63947. // x
  63948. if (point.x < lmin.x) {
  63949. lmin.x = point.x;
  63950. }
  63951. else if (point.x > lmax.x) {
  63952. lmax.x = point.x;
  63953. }
  63954. // y
  63955. if (point.y < lmin.y) {
  63956. lmin.y = point.y;
  63957. }
  63958. else if (point.y > lmax.y) {
  63959. lmax.y = point.y;
  63960. }
  63961. });
  63962. return {
  63963. min: lmin,
  63964. max: lmax,
  63965. width: lmax.x - lmin.x,
  63966. height: lmax.y - lmin.y
  63967. };
  63968. };
  63969. return PolygonPoints;
  63970. }());
  63971. var Polygon = /** @class */ (function () {
  63972. function Polygon() {
  63973. }
  63974. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63975. return [
  63976. new BABYLON.Vector2(xmin, ymin),
  63977. new BABYLON.Vector2(xmax, ymin),
  63978. new BABYLON.Vector2(xmax, ymax),
  63979. new BABYLON.Vector2(xmin, ymax)
  63980. ];
  63981. };
  63982. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63983. if (cx === void 0) { cx = 0; }
  63984. if (cy === void 0) { cy = 0; }
  63985. if (numberOfSides === void 0) { numberOfSides = 32; }
  63986. var result = new Array();
  63987. var angle = 0;
  63988. var increment = (Math.PI * 2) / numberOfSides;
  63989. for (var i = 0; i < numberOfSides; i++) {
  63990. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63991. angle -= increment;
  63992. }
  63993. return result;
  63994. };
  63995. Polygon.Parse = function (input) {
  63996. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63997. var i, result = [];
  63998. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63999. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64000. }
  64001. return result;
  64002. };
  64003. Polygon.StartingAt = function (x, y) {
  64004. return BABYLON.Path2.StartingAt(x, y);
  64005. };
  64006. return Polygon;
  64007. }());
  64008. BABYLON.Polygon = Polygon;
  64009. var PolygonMeshBuilder = /** @class */ (function () {
  64010. function PolygonMeshBuilder(name, contours, scene) {
  64011. this._points = new PolygonPoints();
  64012. this._outlinepoints = new PolygonPoints();
  64013. this._holes = new Array();
  64014. this._epoints = new Array();
  64015. this._eholes = new Array();
  64016. this._name = name;
  64017. this._scene = scene;
  64018. var points;
  64019. if (contours instanceof BABYLON.Path2) {
  64020. points = contours.getPoints();
  64021. }
  64022. else {
  64023. points = contours;
  64024. }
  64025. this._addToepoint(points);
  64026. this._points.add(points);
  64027. this._outlinepoints.add(points);
  64028. }
  64029. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64030. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64031. var p = points_1[_i];
  64032. this._epoints.push(p.x, p.y);
  64033. }
  64034. };
  64035. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64036. this._points.add(hole);
  64037. var holepoints = new PolygonPoints();
  64038. holepoints.add(hole);
  64039. this._holes.push(holepoints);
  64040. this._eholes.push(this._epoints.length / 2);
  64041. this._addToepoint(hole);
  64042. return this;
  64043. };
  64044. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64045. var _this = this;
  64046. if (updatable === void 0) { updatable = false; }
  64047. if (depth === void 0) { depth = 0; }
  64048. var result = new BABYLON.Mesh(this._name, this._scene);
  64049. var normals = new Array();
  64050. var positions = new Array();
  64051. var uvs = new Array();
  64052. var bounds = this._points.computeBounds();
  64053. this._points.elements.forEach(function (p) {
  64054. normals.push(0, 1.0, 0);
  64055. positions.push(p.x, 0, p.y);
  64056. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64057. });
  64058. var indices = new Array();
  64059. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64060. for (var i = 0; i < res.length; i++) {
  64061. indices.push(res[i]);
  64062. }
  64063. if (depth > 0) {
  64064. var positionscount = (positions.length / 3); //get the current pointcount
  64065. this._points.elements.forEach(function (p) {
  64066. normals.push(0, -1.0, 0);
  64067. positions.push(p.x, -depth, p.y);
  64068. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64069. });
  64070. var totalCount = indices.length;
  64071. for (var i = 0; i < totalCount; i += 3) {
  64072. var i0 = indices[i + 0];
  64073. var i1 = indices[i + 1];
  64074. var i2 = indices[i + 2];
  64075. indices.push(i2 + positionscount);
  64076. indices.push(i1 + positionscount);
  64077. indices.push(i0 + positionscount);
  64078. }
  64079. //Add the sides
  64080. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64081. this._holes.forEach(function (hole) {
  64082. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64083. });
  64084. }
  64085. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64086. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64087. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64088. result.setIndices(indices);
  64089. return result;
  64090. };
  64091. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64092. var StartIndex = positions.length / 3;
  64093. var ulength = 0;
  64094. for (var i = 0; i < points.elements.length; i++) {
  64095. var p = points.elements[i];
  64096. var p1;
  64097. if ((i + 1) > points.elements.length - 1) {
  64098. p1 = points.elements[0];
  64099. }
  64100. else {
  64101. p1 = points.elements[i + 1];
  64102. }
  64103. positions.push(p.x, 0, p.y);
  64104. positions.push(p.x, -depth, p.y);
  64105. positions.push(p1.x, 0, p1.y);
  64106. positions.push(p1.x, -depth, p1.y);
  64107. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64108. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64109. var v3 = v2.subtract(v1);
  64110. var v4 = new BABYLON.Vector3(0, 1, 0);
  64111. var vn = BABYLON.Vector3.Cross(v3, v4);
  64112. vn = vn.normalize();
  64113. uvs.push(ulength / bounds.width, 0);
  64114. uvs.push(ulength / bounds.width, 1);
  64115. ulength += v3.length();
  64116. uvs.push((ulength / bounds.width), 0);
  64117. uvs.push((ulength / bounds.width), 1);
  64118. if (!flip) {
  64119. normals.push(-vn.x, -vn.y, -vn.z);
  64120. normals.push(-vn.x, -vn.y, -vn.z);
  64121. normals.push(-vn.x, -vn.y, -vn.z);
  64122. normals.push(-vn.x, -vn.y, -vn.z);
  64123. indices.push(StartIndex);
  64124. indices.push(StartIndex + 1);
  64125. indices.push(StartIndex + 2);
  64126. indices.push(StartIndex + 1);
  64127. indices.push(StartIndex + 3);
  64128. indices.push(StartIndex + 2);
  64129. }
  64130. else {
  64131. normals.push(vn.x, vn.y, vn.z);
  64132. normals.push(vn.x, vn.y, vn.z);
  64133. normals.push(vn.x, vn.y, vn.z);
  64134. normals.push(vn.x, vn.y, vn.z);
  64135. indices.push(StartIndex);
  64136. indices.push(StartIndex + 2);
  64137. indices.push(StartIndex + 1);
  64138. indices.push(StartIndex + 1);
  64139. indices.push(StartIndex + 2);
  64140. indices.push(StartIndex + 3);
  64141. }
  64142. StartIndex += 4;
  64143. }
  64144. ;
  64145. };
  64146. return PolygonMeshBuilder;
  64147. }());
  64148. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64149. })(BABYLON || (BABYLON = {}));
  64150. //# sourceMappingURL=babylon.polygonMesh.js.map
  64151. var BABYLON;
  64152. (function (BABYLON) {
  64153. // Unique ID when we import meshes from Babylon to CSG
  64154. var currentCSGMeshId = 0;
  64155. // # class Vertex
  64156. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64157. // one to provide additional features like texture coordinates and vertex
  64158. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64159. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64160. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64161. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64162. // is not used anywhere else.
  64163. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64164. var Vertex = /** @class */ (function () {
  64165. function Vertex(pos, normal, uv) {
  64166. this.pos = pos;
  64167. this.normal = normal;
  64168. this.uv = uv;
  64169. }
  64170. Vertex.prototype.clone = function () {
  64171. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64172. };
  64173. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64174. // orientation of a polygon is flipped.
  64175. Vertex.prototype.flip = function () {
  64176. this.normal = this.normal.scale(-1);
  64177. };
  64178. // Create a new vertex between this vertex and `other` by linearly
  64179. // interpolating all properties using a parameter of `t`. Subclasses should
  64180. // override this to interpolate additional properties.
  64181. Vertex.prototype.interpolate = function (other, t) {
  64182. 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));
  64183. };
  64184. return Vertex;
  64185. }());
  64186. // # class Plane
  64187. // Represents a plane in 3D space.
  64188. var Plane = /** @class */ (function () {
  64189. function Plane(normal, w) {
  64190. this.normal = normal;
  64191. this.w = w;
  64192. }
  64193. Plane.FromPoints = function (a, b, c) {
  64194. var v0 = c.subtract(a);
  64195. var v1 = b.subtract(a);
  64196. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64197. return null;
  64198. }
  64199. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64200. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64201. };
  64202. Plane.prototype.clone = function () {
  64203. return new Plane(this.normal.clone(), this.w);
  64204. };
  64205. Plane.prototype.flip = function () {
  64206. this.normal.scaleInPlace(-1);
  64207. this.w = -this.w;
  64208. };
  64209. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64210. // fragments in the appropriate lists. Coplanar polygons go into either
  64211. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64212. // respect to this plane. Polygons in front or in back of this plane go into
  64213. // either `front` or `back`.
  64214. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64215. var COPLANAR = 0;
  64216. var FRONT = 1;
  64217. var BACK = 2;
  64218. var SPANNING = 3;
  64219. // Classify each point as well as the entire polygon into one of the above
  64220. // four classes.
  64221. var polygonType = 0;
  64222. var types = [];
  64223. var i;
  64224. var t;
  64225. for (i = 0; i < polygon.vertices.length; i++) {
  64226. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64227. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64228. polygonType |= type;
  64229. types.push(type);
  64230. }
  64231. // Put the polygon in the correct list, splitting it when necessary.
  64232. switch (polygonType) {
  64233. case COPLANAR:
  64234. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64235. break;
  64236. case FRONT:
  64237. front.push(polygon);
  64238. break;
  64239. case BACK:
  64240. back.push(polygon);
  64241. break;
  64242. case SPANNING:
  64243. var f = [], b = [];
  64244. for (i = 0; i < polygon.vertices.length; i++) {
  64245. var j = (i + 1) % polygon.vertices.length;
  64246. var ti = types[i], tj = types[j];
  64247. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64248. if (ti !== BACK)
  64249. f.push(vi);
  64250. if (ti !== FRONT)
  64251. b.push(ti !== BACK ? vi.clone() : vi);
  64252. if ((ti | tj) === SPANNING) {
  64253. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64254. var v = vi.interpolate(vj, t);
  64255. f.push(v);
  64256. b.push(v.clone());
  64257. }
  64258. }
  64259. var poly;
  64260. if (f.length >= 3) {
  64261. poly = new Polygon(f, polygon.shared);
  64262. if (poly.plane)
  64263. front.push(poly);
  64264. }
  64265. if (b.length >= 3) {
  64266. poly = new Polygon(b, polygon.shared);
  64267. if (poly.plane)
  64268. back.push(poly);
  64269. }
  64270. break;
  64271. }
  64272. };
  64273. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64274. // point is on the plane.
  64275. Plane.EPSILON = 1e-5;
  64276. return Plane;
  64277. }());
  64278. // # class Polygon
  64279. // Represents a convex polygon. The vertices used to initialize a polygon must
  64280. // be coplanar and form a convex loop.
  64281. //
  64282. // Each convex polygon has a `shared` property, which is shared between all
  64283. // polygons that are clones of each other or were split from the same polygon.
  64284. // This can be used to define per-polygon properties (such as surface color).
  64285. var Polygon = /** @class */ (function () {
  64286. function Polygon(vertices, shared) {
  64287. this.vertices = vertices;
  64288. this.shared = shared;
  64289. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64290. }
  64291. Polygon.prototype.clone = function () {
  64292. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64293. return new Polygon(vertices, this.shared);
  64294. };
  64295. Polygon.prototype.flip = function () {
  64296. this.vertices.reverse().map(function (v) { v.flip(); });
  64297. this.plane.flip();
  64298. };
  64299. return Polygon;
  64300. }());
  64301. // # class Node
  64302. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64303. // by picking a polygon to split along. That polygon (and all other coplanar
  64304. // polygons) are added directly to that node and the other polygons are added to
  64305. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64306. // no distinction between internal and leaf nodes.
  64307. var Node = /** @class */ (function () {
  64308. function Node(polygons) {
  64309. this.plane = null;
  64310. this.front = null;
  64311. this.back = null;
  64312. this.polygons = new Array();
  64313. if (polygons) {
  64314. this.build(polygons);
  64315. }
  64316. }
  64317. Node.prototype.clone = function () {
  64318. var node = new Node();
  64319. node.plane = this.plane && this.plane.clone();
  64320. node.front = this.front && this.front.clone();
  64321. node.back = this.back && this.back.clone();
  64322. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64323. return node;
  64324. };
  64325. // Convert solid space to empty space and empty space to solid space.
  64326. Node.prototype.invert = function () {
  64327. for (var i = 0; i < this.polygons.length; i++) {
  64328. this.polygons[i].flip();
  64329. }
  64330. if (this.plane) {
  64331. this.plane.flip();
  64332. }
  64333. if (this.front) {
  64334. this.front.invert();
  64335. }
  64336. if (this.back) {
  64337. this.back.invert();
  64338. }
  64339. var temp = this.front;
  64340. this.front = this.back;
  64341. this.back = temp;
  64342. };
  64343. // Recursively remove all polygons in `polygons` that are inside this BSP
  64344. // tree.
  64345. Node.prototype.clipPolygons = function (polygons) {
  64346. if (!this.plane)
  64347. return polygons.slice();
  64348. var front = new Array(), back = new Array();
  64349. for (var i = 0; i < polygons.length; i++) {
  64350. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64351. }
  64352. if (this.front) {
  64353. front = this.front.clipPolygons(front);
  64354. }
  64355. if (this.back) {
  64356. back = this.back.clipPolygons(back);
  64357. }
  64358. else {
  64359. back = [];
  64360. }
  64361. return front.concat(back);
  64362. };
  64363. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64364. // `bsp`.
  64365. Node.prototype.clipTo = function (bsp) {
  64366. this.polygons = bsp.clipPolygons(this.polygons);
  64367. if (this.front)
  64368. this.front.clipTo(bsp);
  64369. if (this.back)
  64370. this.back.clipTo(bsp);
  64371. };
  64372. // Return a list of all polygons in this BSP tree.
  64373. Node.prototype.allPolygons = function () {
  64374. var polygons = this.polygons.slice();
  64375. if (this.front)
  64376. polygons = polygons.concat(this.front.allPolygons());
  64377. if (this.back)
  64378. polygons = polygons.concat(this.back.allPolygons());
  64379. return polygons;
  64380. };
  64381. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64382. // new polygons are filtered down to the bottom of the tree and become new
  64383. // nodes there. Each set of polygons is partitioned using the first polygon
  64384. // (no heuristic is used to pick a good split).
  64385. Node.prototype.build = function (polygons) {
  64386. if (!polygons.length)
  64387. return;
  64388. if (!this.plane)
  64389. this.plane = polygons[0].plane.clone();
  64390. var front = new Array(), back = new Array();
  64391. for (var i = 0; i < polygons.length; i++) {
  64392. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64393. }
  64394. if (front.length) {
  64395. if (!this.front)
  64396. this.front = new Node();
  64397. this.front.build(front);
  64398. }
  64399. if (back.length) {
  64400. if (!this.back)
  64401. this.back = new Node();
  64402. this.back.build(back);
  64403. }
  64404. };
  64405. return Node;
  64406. }());
  64407. var CSG = /** @class */ (function () {
  64408. function CSG() {
  64409. this.polygons = new Array();
  64410. }
  64411. // Convert BABYLON.Mesh to BABYLON.CSG
  64412. CSG.FromMesh = function (mesh) {
  64413. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64414. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64415. if (mesh instanceof BABYLON.Mesh) {
  64416. mesh.computeWorldMatrix(true);
  64417. matrix = mesh.getWorldMatrix();
  64418. meshPosition = mesh.position.clone();
  64419. meshRotation = mesh.rotation.clone();
  64420. if (mesh.rotationQuaternion) {
  64421. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64422. }
  64423. meshScaling = mesh.scaling.clone();
  64424. }
  64425. else {
  64426. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64427. }
  64428. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64429. var subMeshes = mesh.subMeshes;
  64430. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64431. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64432. vertices = [];
  64433. for (var j = 0; j < 3; j++) {
  64434. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64435. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64436. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64437. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64438. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64439. vertex = new Vertex(position, normal, uv);
  64440. vertices.push(vertex);
  64441. }
  64442. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64443. // To handle the case of degenerated triangle
  64444. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64445. if (polygon.plane)
  64446. polygons.push(polygon);
  64447. }
  64448. }
  64449. var csg = CSG.FromPolygons(polygons);
  64450. csg.matrix = matrix;
  64451. csg.position = meshPosition;
  64452. csg.rotation = meshRotation;
  64453. csg.scaling = meshScaling;
  64454. csg.rotationQuaternion = meshRotationQuaternion;
  64455. currentCSGMeshId++;
  64456. return csg;
  64457. };
  64458. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64459. CSG.FromPolygons = function (polygons) {
  64460. var csg = new CSG();
  64461. csg.polygons = polygons;
  64462. return csg;
  64463. };
  64464. CSG.prototype.clone = function () {
  64465. var csg = new CSG();
  64466. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64467. csg.copyTransformAttributes(this);
  64468. return csg;
  64469. };
  64470. CSG.prototype.union = function (csg) {
  64471. var a = new Node(this.clone().polygons);
  64472. var b = new Node(csg.clone().polygons);
  64473. a.clipTo(b);
  64474. b.clipTo(a);
  64475. b.invert();
  64476. b.clipTo(a);
  64477. b.invert();
  64478. a.build(b.allPolygons());
  64479. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64480. };
  64481. CSG.prototype.unionInPlace = function (csg) {
  64482. var a = new Node(this.polygons);
  64483. var b = new Node(csg.polygons);
  64484. a.clipTo(b);
  64485. b.clipTo(a);
  64486. b.invert();
  64487. b.clipTo(a);
  64488. b.invert();
  64489. a.build(b.allPolygons());
  64490. this.polygons = a.allPolygons();
  64491. };
  64492. CSG.prototype.subtract = function (csg) {
  64493. var a = new Node(this.clone().polygons);
  64494. var b = new Node(csg.clone().polygons);
  64495. a.invert();
  64496. a.clipTo(b);
  64497. b.clipTo(a);
  64498. b.invert();
  64499. b.clipTo(a);
  64500. b.invert();
  64501. a.build(b.allPolygons());
  64502. a.invert();
  64503. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64504. };
  64505. CSG.prototype.subtractInPlace = function (csg) {
  64506. var a = new Node(this.polygons);
  64507. var b = new Node(csg.polygons);
  64508. a.invert();
  64509. a.clipTo(b);
  64510. b.clipTo(a);
  64511. b.invert();
  64512. b.clipTo(a);
  64513. b.invert();
  64514. a.build(b.allPolygons());
  64515. a.invert();
  64516. this.polygons = a.allPolygons();
  64517. };
  64518. CSG.prototype.intersect = function (csg) {
  64519. var a = new Node(this.clone().polygons);
  64520. var b = new Node(csg.clone().polygons);
  64521. a.invert();
  64522. b.clipTo(a);
  64523. b.invert();
  64524. a.clipTo(b);
  64525. b.clipTo(a);
  64526. a.build(b.allPolygons());
  64527. a.invert();
  64528. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64529. };
  64530. CSG.prototype.intersectInPlace = function (csg) {
  64531. var a = new Node(this.polygons);
  64532. var b = new Node(csg.polygons);
  64533. a.invert();
  64534. b.clipTo(a);
  64535. b.invert();
  64536. a.clipTo(b);
  64537. b.clipTo(a);
  64538. a.build(b.allPolygons());
  64539. a.invert();
  64540. this.polygons = a.allPolygons();
  64541. };
  64542. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64543. // not modified.
  64544. CSG.prototype.inverse = function () {
  64545. var csg = this.clone();
  64546. csg.inverseInPlace();
  64547. return csg;
  64548. };
  64549. CSG.prototype.inverseInPlace = function () {
  64550. this.polygons.map(function (p) { p.flip(); });
  64551. };
  64552. // This is used to keep meshes transformations so they can be restored
  64553. // when we build back a Babylon Mesh
  64554. // NB : All CSG operations are performed in world coordinates
  64555. CSG.prototype.copyTransformAttributes = function (csg) {
  64556. this.matrix = csg.matrix;
  64557. this.position = csg.position;
  64558. this.rotation = csg.rotation;
  64559. this.scaling = csg.scaling;
  64560. this.rotationQuaternion = csg.rotationQuaternion;
  64561. return this;
  64562. };
  64563. // Build Raw mesh from CSG
  64564. // Coordinates here are in world space
  64565. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64566. var matrix = this.matrix.clone();
  64567. matrix.invert();
  64568. 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;
  64569. if (keepSubMeshes) {
  64570. // Sort Polygons, since subMeshes are indices range
  64571. polygons.sort(function (a, b) {
  64572. if (a.shared.meshId === b.shared.meshId) {
  64573. return a.shared.subMeshId - b.shared.subMeshId;
  64574. }
  64575. else {
  64576. return a.shared.meshId - b.shared.meshId;
  64577. }
  64578. });
  64579. }
  64580. for (var i = 0, il = polygons.length; i < il; i++) {
  64581. polygon = polygons[i];
  64582. // Building SubMeshes
  64583. if (!subMesh_dict[polygon.shared.meshId]) {
  64584. subMesh_dict[polygon.shared.meshId] = {};
  64585. }
  64586. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64587. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64588. indexStart: +Infinity,
  64589. indexEnd: -Infinity,
  64590. materialIndex: polygon.shared.materialIndex
  64591. };
  64592. }
  64593. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64594. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64595. polygonIndices[0] = 0;
  64596. polygonIndices[1] = j - 1;
  64597. polygonIndices[2] = j;
  64598. for (var k = 0; k < 3; k++) {
  64599. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64600. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64601. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64602. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64603. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64604. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64605. // Check if 2 points can be merged
  64606. if (!(typeof vertex_idx !== 'undefined' &&
  64607. normals[vertex_idx * 3] === localNormal.x &&
  64608. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64609. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64610. uvs[vertex_idx * 2] === uv.x &&
  64611. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64612. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64613. uvs.push(uv.x, uv.y);
  64614. normals.push(normal.x, normal.y, normal.z);
  64615. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64616. }
  64617. indices.push(vertex_idx);
  64618. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64619. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64620. currentIndex++;
  64621. }
  64622. }
  64623. }
  64624. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64625. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64626. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64627. mesh.setIndices(indices, null);
  64628. if (keepSubMeshes) {
  64629. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64630. var materialIndexOffset = 0, materialMaxIndex;
  64631. mesh.subMeshes = new Array();
  64632. for (var m in subMesh_dict) {
  64633. materialMaxIndex = -1;
  64634. for (var sm in subMesh_dict[m]) {
  64635. subMesh_obj = subMesh_dict[m][sm];
  64636. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64637. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64638. }
  64639. materialIndexOffset += ++materialMaxIndex;
  64640. }
  64641. }
  64642. return mesh;
  64643. };
  64644. // Build Mesh from CSG taking material and transforms into account
  64645. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64646. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64647. mesh.material = material;
  64648. mesh.position.copyFrom(this.position);
  64649. mesh.rotation.copyFrom(this.rotation);
  64650. if (this.rotationQuaternion) {
  64651. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64652. }
  64653. mesh.scaling.copyFrom(this.scaling);
  64654. mesh.computeWorldMatrix(true);
  64655. return mesh;
  64656. };
  64657. return CSG;
  64658. }());
  64659. BABYLON.CSG = CSG;
  64660. })(BABYLON || (BABYLON = {}));
  64661. //# sourceMappingURL=babylon.csg.js.map
  64662. var BABYLON;
  64663. (function (BABYLON) {
  64664. var LensFlare = /** @class */ (function () {
  64665. function LensFlare(size, position, color, imgUrl, system) {
  64666. this.size = size;
  64667. this.position = position;
  64668. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64669. this.color = color || new BABYLON.Color3(1, 1, 1);
  64670. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64671. this._system = system;
  64672. system.lensFlares.push(this);
  64673. }
  64674. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64675. return new LensFlare(size, position, color, imgUrl, system);
  64676. };
  64677. LensFlare.prototype.dispose = function () {
  64678. if (this.texture) {
  64679. this.texture.dispose();
  64680. }
  64681. // Remove from scene
  64682. var index = this._system.lensFlares.indexOf(this);
  64683. this._system.lensFlares.splice(index, 1);
  64684. };
  64685. ;
  64686. return LensFlare;
  64687. }());
  64688. BABYLON.LensFlare = LensFlare;
  64689. })(BABYLON || (BABYLON = {}));
  64690. //# sourceMappingURL=babylon.lensFlare.js.map
  64691. var BABYLON;
  64692. (function (BABYLON) {
  64693. var LensFlareSystem = /** @class */ (function () {
  64694. function LensFlareSystem(name, emitter, scene) {
  64695. this.name = name;
  64696. this.lensFlares = new Array();
  64697. this.borderLimit = 300;
  64698. this.viewportBorder = 0;
  64699. this.layerMask = 0x0FFFFFFF;
  64700. this._vertexBuffers = {};
  64701. this._isEnabled = true;
  64702. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64703. this._emitter = emitter;
  64704. this.id = name;
  64705. scene.lensFlareSystems.push(this);
  64706. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64707. var engine = scene.getEngine();
  64708. // VBO
  64709. var vertices = [];
  64710. vertices.push(1, 1);
  64711. vertices.push(-1, 1);
  64712. vertices.push(-1, -1);
  64713. vertices.push(1, -1);
  64714. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64715. // Indices
  64716. var indices = [];
  64717. indices.push(0);
  64718. indices.push(1);
  64719. indices.push(2);
  64720. indices.push(0);
  64721. indices.push(2);
  64722. indices.push(3);
  64723. this._indexBuffer = engine.createIndexBuffer(indices);
  64724. // Effects
  64725. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64726. }
  64727. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64728. get: function () {
  64729. return this._isEnabled;
  64730. },
  64731. set: function (value) {
  64732. this._isEnabled = value;
  64733. },
  64734. enumerable: true,
  64735. configurable: true
  64736. });
  64737. LensFlareSystem.prototype.getScene = function () {
  64738. return this._scene;
  64739. };
  64740. LensFlareSystem.prototype.getEmitter = function () {
  64741. return this._emitter;
  64742. };
  64743. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64744. this._emitter = newEmitter;
  64745. };
  64746. LensFlareSystem.prototype.getEmitterPosition = function () {
  64747. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64748. };
  64749. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64750. var position = this.getEmitterPosition();
  64751. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64752. this._positionX = position.x;
  64753. this._positionY = position.y;
  64754. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64755. if (this.viewportBorder > 0) {
  64756. globalViewport.x -= this.viewportBorder;
  64757. globalViewport.y -= this.viewportBorder;
  64758. globalViewport.width += this.viewportBorder * 2;
  64759. globalViewport.height += this.viewportBorder * 2;
  64760. position.x += this.viewportBorder;
  64761. position.y += this.viewportBorder;
  64762. this._positionX += this.viewportBorder;
  64763. this._positionY += this.viewportBorder;
  64764. }
  64765. if (position.z > 0) {
  64766. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64767. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64768. return true;
  64769. }
  64770. return true;
  64771. }
  64772. return false;
  64773. };
  64774. LensFlareSystem.prototype._isVisible = function () {
  64775. if (!this._isEnabled || !this._scene.activeCamera) {
  64776. return false;
  64777. }
  64778. var emitterPosition = this.getEmitterPosition();
  64779. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64780. var distance = direction.length();
  64781. direction.normalize();
  64782. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64783. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64784. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64785. };
  64786. LensFlareSystem.prototype.render = function () {
  64787. if (!this._effect.isReady() || !this._scene.activeCamera)
  64788. return false;
  64789. var engine = this._scene.getEngine();
  64790. var viewport = this._scene.activeCamera.viewport;
  64791. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64792. // Position
  64793. if (!this.computeEffectivePosition(globalViewport)) {
  64794. return false;
  64795. }
  64796. // Visibility
  64797. if (!this._isVisible()) {
  64798. return false;
  64799. }
  64800. // Intensity
  64801. var awayX;
  64802. var awayY;
  64803. if (this._positionX < this.borderLimit + globalViewport.x) {
  64804. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64805. }
  64806. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64807. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64808. }
  64809. else {
  64810. awayX = 0;
  64811. }
  64812. if (this._positionY < this.borderLimit + globalViewport.y) {
  64813. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64814. }
  64815. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64816. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64817. }
  64818. else {
  64819. awayY = 0;
  64820. }
  64821. var away = (awayX > awayY) ? awayX : awayY;
  64822. away -= this.viewportBorder;
  64823. if (away > this.borderLimit) {
  64824. away = this.borderLimit;
  64825. }
  64826. var intensity = 1.0 - (away / this.borderLimit);
  64827. if (intensity < 0) {
  64828. return false;
  64829. }
  64830. if (intensity > 1.0) {
  64831. intensity = 1.0;
  64832. }
  64833. if (this.viewportBorder > 0) {
  64834. globalViewport.x += this.viewportBorder;
  64835. globalViewport.y += this.viewportBorder;
  64836. globalViewport.width -= this.viewportBorder * 2;
  64837. globalViewport.height -= this.viewportBorder * 2;
  64838. this._positionX -= this.viewportBorder;
  64839. this._positionY -= this.viewportBorder;
  64840. }
  64841. // Position
  64842. var centerX = globalViewport.x + globalViewport.width / 2;
  64843. var centerY = globalViewport.y + globalViewport.height / 2;
  64844. var distX = centerX - this._positionX;
  64845. var distY = centerY - this._positionY;
  64846. // Effects
  64847. engine.enableEffect(this._effect);
  64848. engine.setState(false);
  64849. engine.setDepthBuffer(false);
  64850. // VBOs
  64851. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64852. // Flares
  64853. for (var index = 0; index < this.lensFlares.length; index++) {
  64854. var flare = this.lensFlares[index];
  64855. engine.setAlphaMode(flare.alphaMode);
  64856. var x = centerX - (distX * flare.position);
  64857. var y = centerY - (distY * flare.position);
  64858. var cw = flare.size;
  64859. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64860. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64861. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64862. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64863. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64864. // Texture
  64865. this._effect.setTexture("textureSampler", flare.texture);
  64866. // Color
  64867. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64868. // Draw order
  64869. engine.draw(true, 0, 6);
  64870. }
  64871. engine.setDepthBuffer(true);
  64872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64873. return true;
  64874. };
  64875. LensFlareSystem.prototype.dispose = function () {
  64876. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64877. if (vertexBuffer) {
  64878. vertexBuffer.dispose();
  64879. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64880. }
  64881. if (this._indexBuffer) {
  64882. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64883. this._indexBuffer = null;
  64884. }
  64885. while (this.lensFlares.length) {
  64886. this.lensFlares[0].dispose();
  64887. }
  64888. // Remove from scene
  64889. var index = this._scene.lensFlareSystems.indexOf(this);
  64890. this._scene.lensFlareSystems.splice(index, 1);
  64891. };
  64892. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64893. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64894. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64895. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64896. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64897. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64898. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64899. var parsedFlare = parsedLensFlareSystem.flares[index];
  64900. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64901. }
  64902. return lensFlareSystem;
  64903. };
  64904. LensFlareSystem.prototype.serialize = function () {
  64905. var serializationObject = {};
  64906. serializationObject.id = this.id;
  64907. serializationObject.name = this.name;
  64908. serializationObject.emitterId = this.getEmitter().id;
  64909. serializationObject.borderLimit = this.borderLimit;
  64910. serializationObject.flares = [];
  64911. for (var index = 0; index < this.lensFlares.length; index++) {
  64912. var flare = this.lensFlares[index];
  64913. serializationObject.flares.push({
  64914. size: flare.size,
  64915. position: flare.position,
  64916. color: flare.color.asArray(),
  64917. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64918. });
  64919. }
  64920. return serializationObject;
  64921. };
  64922. return LensFlareSystem;
  64923. }());
  64924. BABYLON.LensFlareSystem = LensFlareSystem;
  64925. })(BABYLON || (BABYLON = {}));
  64926. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64927. var BABYLON;
  64928. (function (BABYLON) {
  64929. /**
  64930. * This is a holder class for the physics joint created by the physics plugin.
  64931. * It holds a set of functions to control the underlying joint.
  64932. */
  64933. var PhysicsJoint = /** @class */ (function () {
  64934. function PhysicsJoint(type, jointData) {
  64935. this.type = type;
  64936. this.jointData = jointData;
  64937. jointData.nativeParams = jointData.nativeParams || {};
  64938. }
  64939. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64940. get: function () {
  64941. return this._physicsJoint;
  64942. },
  64943. set: function (newJoint) {
  64944. if (this._physicsJoint) {
  64945. //remove from the wolrd
  64946. }
  64947. this._physicsJoint = newJoint;
  64948. },
  64949. enumerable: true,
  64950. configurable: true
  64951. });
  64952. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64953. set: function (physicsPlugin) {
  64954. this._physicsPlugin = physicsPlugin;
  64955. },
  64956. enumerable: true,
  64957. configurable: true
  64958. });
  64959. /**
  64960. * Execute a function that is physics-plugin specific.
  64961. * @param {Function} func the function that will be executed.
  64962. * It accepts two parameters: the physics world and the physics joint.
  64963. */
  64964. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64965. func(this._physicsPlugin.world, this._physicsJoint);
  64966. };
  64967. //TODO check if the native joints are the same
  64968. //Joint Types
  64969. PhysicsJoint.DistanceJoint = 0;
  64970. PhysicsJoint.HingeJoint = 1;
  64971. PhysicsJoint.BallAndSocketJoint = 2;
  64972. PhysicsJoint.WheelJoint = 3;
  64973. PhysicsJoint.SliderJoint = 4;
  64974. //OIMO
  64975. PhysicsJoint.PrismaticJoint = 5;
  64976. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64977. PhysicsJoint.UniversalJoint = 6;
  64978. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64979. //Cannon
  64980. //Similar to a Ball-Joint. Different in params
  64981. PhysicsJoint.PointToPointJoint = 8;
  64982. //Cannon only at the moment
  64983. PhysicsJoint.SpringJoint = 9;
  64984. PhysicsJoint.LockJoint = 10;
  64985. return PhysicsJoint;
  64986. }());
  64987. BABYLON.PhysicsJoint = PhysicsJoint;
  64988. /**
  64989. * A class representing a physics distance joint.
  64990. */
  64991. var DistanceJoint = /** @class */ (function (_super) {
  64992. __extends(DistanceJoint, _super);
  64993. function DistanceJoint(jointData) {
  64994. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64995. }
  64996. /**
  64997. * Update the predefined distance.
  64998. */
  64999. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65000. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65001. };
  65002. return DistanceJoint;
  65003. }(PhysicsJoint));
  65004. BABYLON.DistanceJoint = DistanceJoint;
  65005. var MotorEnabledJoint = /** @class */ (function (_super) {
  65006. __extends(MotorEnabledJoint, _super);
  65007. function MotorEnabledJoint(type, jointData) {
  65008. return _super.call(this, type, jointData) || this;
  65009. }
  65010. /**
  65011. * Set the motor values.
  65012. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65013. * @param {number} force the force to apply
  65014. * @param {number} maxForce max force for this motor.
  65015. */
  65016. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65017. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65018. };
  65019. /**
  65020. * Set the motor's limits.
  65021. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65022. */
  65023. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65024. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65025. };
  65026. return MotorEnabledJoint;
  65027. }(PhysicsJoint));
  65028. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65029. /**
  65030. * This class represents a single hinge physics joint
  65031. */
  65032. var HingeJoint = /** @class */ (function (_super) {
  65033. __extends(HingeJoint, _super);
  65034. function HingeJoint(jointData) {
  65035. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65036. }
  65037. /**
  65038. * Set the motor values.
  65039. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65040. * @param {number} force the force to apply
  65041. * @param {number} maxForce max force for this motor.
  65042. */
  65043. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65044. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65045. };
  65046. /**
  65047. * Set the motor's limits.
  65048. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65049. */
  65050. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65051. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65052. };
  65053. return HingeJoint;
  65054. }(MotorEnabledJoint));
  65055. BABYLON.HingeJoint = HingeJoint;
  65056. /**
  65057. * This class represents a dual hinge physics joint (same as wheel joint)
  65058. */
  65059. var Hinge2Joint = /** @class */ (function (_super) {
  65060. __extends(Hinge2Joint, _super);
  65061. function Hinge2Joint(jointData) {
  65062. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65063. }
  65064. /**
  65065. * Set the motor values.
  65066. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65067. * @param {number} force the force to apply
  65068. * @param {number} maxForce max force for this motor.
  65069. * @param {motorIndex} the motor's index, 0 or 1.
  65070. */
  65071. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65072. if (motorIndex === void 0) { motorIndex = 0; }
  65073. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65074. };
  65075. /**
  65076. * Set the motor limits.
  65077. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65078. * @param {number} upperLimit the upper limit
  65079. * @param {number} lowerLimit lower limit
  65080. * @param {motorIndex} the motor's index, 0 or 1.
  65081. */
  65082. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65083. if (motorIndex === void 0) { motorIndex = 0; }
  65084. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65085. };
  65086. return Hinge2Joint;
  65087. }(MotorEnabledJoint));
  65088. BABYLON.Hinge2Joint = Hinge2Joint;
  65089. })(BABYLON || (BABYLON = {}));
  65090. //# sourceMappingURL=babylon.physicsJoint.js.map
  65091. var BABYLON;
  65092. (function (BABYLON) {
  65093. var PhysicsImpostor = /** @class */ (function () {
  65094. function PhysicsImpostor(object, type, _options, _scene) {
  65095. if (_options === void 0) { _options = { mass: 0 }; }
  65096. var _this = this;
  65097. this.object = object;
  65098. this.type = type;
  65099. this._options = _options;
  65100. this._scene = _scene;
  65101. this._bodyUpdateRequired = false;
  65102. this._onBeforePhysicsStepCallbacks = new Array();
  65103. this._onAfterPhysicsStepCallbacks = new Array();
  65104. this._onPhysicsCollideCallbacks = [];
  65105. this._deltaPosition = BABYLON.Vector3.Zero();
  65106. this._isDisposed = false;
  65107. //temp variables for parent rotation calculations
  65108. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65109. this._tmpQuat = new BABYLON.Quaternion();
  65110. this._tmpQuat2 = new BABYLON.Quaternion();
  65111. /**
  65112. * this function is executed by the physics engine.
  65113. */
  65114. this.beforeStep = function () {
  65115. if (!_this._physicsEngine) {
  65116. return;
  65117. }
  65118. _this.object.translate(_this._deltaPosition, -1);
  65119. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65120. if (_this.object.parent && _this.object.rotationQuaternion) {
  65121. _this.getParentsRotation();
  65122. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65123. }
  65124. else {
  65125. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65126. }
  65127. if (!_this._options.disableBidirectionalTransformation) {
  65128. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65129. }
  65130. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65131. func(_this);
  65132. });
  65133. };
  65134. /**
  65135. * this function is executed by the physics engine.
  65136. */
  65137. this.afterStep = function () {
  65138. if (!_this._physicsEngine) {
  65139. return;
  65140. }
  65141. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65142. // object has now its world rotation. needs to be converted to local.
  65143. if (_this.object.parent && _this.object.rotationQuaternion) {
  65144. _this.getParentsRotation();
  65145. _this._tmpQuat.conjugateInPlace();
  65146. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65147. }
  65148. // take the position set and make it the absolute position of this object.
  65149. _this.object.setAbsolutePosition(_this.object.position);
  65150. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65151. _this.object.translate(_this._deltaPosition, 1);
  65152. };
  65153. /**
  65154. * Legacy collision detection event support
  65155. */
  65156. this.onCollideEvent = null;
  65157. //event and body object due to cannon's event-based architecture.
  65158. this.onCollide = function (e) {
  65159. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65160. return;
  65161. }
  65162. if (!_this._physicsEngine) {
  65163. return;
  65164. }
  65165. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65166. if (otherImpostor) {
  65167. // Legacy collision detection event support
  65168. if (_this.onCollideEvent) {
  65169. _this.onCollideEvent(_this, otherImpostor);
  65170. }
  65171. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65172. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65173. }).forEach(function (obj) {
  65174. obj.callback(_this, otherImpostor);
  65175. });
  65176. }
  65177. };
  65178. //sanity check!
  65179. if (!this.object) {
  65180. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65181. return;
  65182. }
  65183. //legacy support for old syntax.
  65184. if (!this._scene && object.getScene) {
  65185. this._scene = object.getScene();
  65186. }
  65187. if (!this._scene) {
  65188. return;
  65189. }
  65190. this._physicsEngine = this._scene.getPhysicsEngine();
  65191. if (!this._physicsEngine) {
  65192. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65193. }
  65194. else {
  65195. //set the object's quaternion, if not set
  65196. if (!this.object.rotationQuaternion) {
  65197. if (this.object.rotation) {
  65198. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65199. }
  65200. else {
  65201. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65202. }
  65203. }
  65204. //default options params
  65205. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65206. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65207. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65208. this._joints = [];
  65209. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65210. if (!this.object.parent || this._options.ignoreParent) {
  65211. this._init();
  65212. }
  65213. else if (this.object.parent.physicsImpostor) {
  65214. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65215. }
  65216. }
  65217. }
  65218. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65219. get: function () {
  65220. return this._isDisposed;
  65221. },
  65222. enumerable: true,
  65223. configurable: true
  65224. });
  65225. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65226. get: function () {
  65227. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65228. },
  65229. set: function (value) {
  65230. this.setMass(value);
  65231. },
  65232. enumerable: true,
  65233. configurable: true
  65234. });
  65235. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65236. get: function () {
  65237. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65238. },
  65239. set: function (value) {
  65240. if (!this._physicsEngine) {
  65241. return;
  65242. }
  65243. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65244. },
  65245. enumerable: true,
  65246. configurable: true
  65247. });
  65248. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65249. get: function () {
  65250. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65251. },
  65252. set: function (value) {
  65253. if (!this._physicsEngine) {
  65254. return;
  65255. }
  65256. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65257. },
  65258. enumerable: true,
  65259. configurable: true
  65260. });
  65261. /**
  65262. * This function will completly initialize this impostor.
  65263. * It will create a new body - but only if this mesh has no parent.
  65264. * If it has, this impostor will not be used other than to define the impostor
  65265. * of the child mesh.
  65266. */
  65267. PhysicsImpostor.prototype._init = function () {
  65268. if (!this._physicsEngine) {
  65269. return;
  65270. }
  65271. this._physicsEngine.removeImpostor(this);
  65272. this.physicsBody = null;
  65273. this._parent = this._parent || this._getPhysicsParent();
  65274. if (!this.parent || this._options.ignoreParent) {
  65275. this._physicsEngine.addImpostor(this);
  65276. }
  65277. };
  65278. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65279. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65280. var parentMesh = this.object.parent;
  65281. return parentMesh.physicsImpostor;
  65282. }
  65283. return null;
  65284. };
  65285. /**
  65286. * Should a new body be generated.
  65287. */
  65288. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65289. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65290. };
  65291. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65292. this.forceUpdate();
  65293. };
  65294. /**
  65295. * Force a regeneration of this or the parent's impostor's body.
  65296. * Use under cautious - This will remove all joints already implemented.
  65297. */
  65298. PhysicsImpostor.prototype.forceUpdate = function () {
  65299. this._init();
  65300. if (this.parent && !this._options.ignoreParent) {
  65301. this.parent.forceUpdate();
  65302. }
  65303. };
  65304. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65305. /*public get mesh(): AbstractMesh {
  65306. return this._mesh;
  65307. }*/
  65308. /**
  65309. * Gets the body that holds this impostor. Either its own, or its parent.
  65310. */
  65311. get: function () {
  65312. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65313. },
  65314. /**
  65315. * Set the physics body. Used mainly by the physics engine/plugin
  65316. */
  65317. set: function (physicsBody) {
  65318. if (this._physicsBody && this._physicsEngine) {
  65319. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65320. }
  65321. this._physicsBody = physicsBody;
  65322. this.resetUpdateFlags();
  65323. },
  65324. enumerable: true,
  65325. configurable: true
  65326. });
  65327. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65328. get: function () {
  65329. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65330. },
  65331. set: function (value) {
  65332. this._parent = value;
  65333. },
  65334. enumerable: true,
  65335. configurable: true
  65336. });
  65337. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65338. this._bodyUpdateRequired = false;
  65339. };
  65340. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65341. if (this.object.getBoundingInfo) {
  65342. var q = this.object.rotationQuaternion;
  65343. //reset rotation
  65344. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65345. //calculate the world matrix with no rotation
  65346. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65347. var boundingInfo = this.object.getBoundingInfo();
  65348. var size = void 0;
  65349. if (boundingInfo) {
  65350. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65351. }
  65352. else {
  65353. size = BABYLON.Vector3.Zero();
  65354. }
  65355. //bring back the rotation
  65356. this.object.rotationQuaternion = q;
  65357. //calculate the world matrix with the new rotation
  65358. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65359. return size;
  65360. }
  65361. else {
  65362. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65363. }
  65364. };
  65365. PhysicsImpostor.prototype.getObjectCenter = function () {
  65366. if (this.object.getBoundingInfo) {
  65367. var boundingInfo = this.object.getBoundingInfo();
  65368. if (!boundingInfo) {
  65369. return this.object.position;
  65370. }
  65371. return boundingInfo.boundingBox.centerWorld;
  65372. }
  65373. else {
  65374. return this.object.position;
  65375. }
  65376. };
  65377. /**
  65378. * Get a specific parametes from the options parameter.
  65379. */
  65380. PhysicsImpostor.prototype.getParam = function (paramName) {
  65381. return this._options[paramName];
  65382. };
  65383. /**
  65384. * Sets a specific parameter in the options given to the physics plugin
  65385. */
  65386. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65387. this._options[paramName] = value;
  65388. this._bodyUpdateRequired = true;
  65389. };
  65390. /**
  65391. * Specifically change the body's mass option. Won't recreate the physics body object
  65392. */
  65393. PhysicsImpostor.prototype.setMass = function (mass) {
  65394. if (this.getParam("mass") !== mass) {
  65395. this.setParam("mass", mass);
  65396. }
  65397. if (this._physicsEngine) {
  65398. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65399. }
  65400. };
  65401. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65402. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65403. };
  65404. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65405. if (this._physicsEngine) {
  65406. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65407. }
  65408. };
  65409. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65410. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65411. };
  65412. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65413. if (this._physicsEngine) {
  65414. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65415. }
  65416. };
  65417. /**
  65418. * Execute a function with the physics plugin native code.
  65419. * Provide a function the will have two variables - the world object and the physics body object.
  65420. */
  65421. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65422. if (this._physicsEngine) {
  65423. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65424. }
  65425. };
  65426. /**
  65427. * Register a function that will be executed before the physics world is stepping forward.
  65428. */
  65429. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65430. this._onBeforePhysicsStepCallbacks.push(func);
  65431. };
  65432. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65433. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65434. if (index > -1) {
  65435. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65436. }
  65437. else {
  65438. BABYLON.Tools.Warn("Function to remove was not found");
  65439. }
  65440. };
  65441. /**
  65442. * Register a function that will be executed after the physics step
  65443. */
  65444. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65445. this._onAfterPhysicsStepCallbacks.push(func);
  65446. };
  65447. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65448. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65449. if (index > -1) {
  65450. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65451. }
  65452. else {
  65453. BABYLON.Tools.Warn("Function to remove was not found");
  65454. }
  65455. };
  65456. /**
  65457. * register a function that will be executed when this impostor collides against a different body.
  65458. */
  65459. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65460. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65461. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65462. };
  65463. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65464. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65465. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65466. if (index > -1) {
  65467. this._onPhysicsCollideCallbacks.splice(index, 1);
  65468. }
  65469. else {
  65470. BABYLON.Tools.Warn("Function to remove was not found");
  65471. }
  65472. };
  65473. PhysicsImpostor.prototype.getParentsRotation = function () {
  65474. var parent = this.object.parent;
  65475. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  65476. while (parent) {
  65477. if (parent.rotationQuaternion) {
  65478. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  65479. }
  65480. else {
  65481. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  65482. }
  65483. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  65484. parent = parent.parent;
  65485. }
  65486. return this._tmpQuat;
  65487. };
  65488. /**
  65489. * Apply a force
  65490. */
  65491. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65492. if (this._physicsEngine) {
  65493. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65494. }
  65495. return this;
  65496. };
  65497. /**
  65498. * Apply an impulse
  65499. */
  65500. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65501. if (this._physicsEngine) {
  65502. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65503. }
  65504. return this;
  65505. };
  65506. /**
  65507. * A help function to create a joint.
  65508. */
  65509. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65510. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65511. this.addJoint(otherImpostor, joint);
  65512. return this;
  65513. };
  65514. /**
  65515. * Add a joint to this impostor with a different impostor.
  65516. */
  65517. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65518. this._joints.push({
  65519. otherImpostor: otherImpostor,
  65520. joint: joint
  65521. });
  65522. if (this._physicsEngine) {
  65523. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65524. }
  65525. return this;
  65526. };
  65527. /**
  65528. * Will keep this body still, in a sleep mode.
  65529. */
  65530. PhysicsImpostor.prototype.sleep = function () {
  65531. if (this._physicsEngine) {
  65532. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65533. }
  65534. return this;
  65535. };
  65536. /**
  65537. * Wake the body up.
  65538. */
  65539. PhysicsImpostor.prototype.wakeUp = function () {
  65540. if (this._physicsEngine) {
  65541. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65542. }
  65543. return this;
  65544. };
  65545. PhysicsImpostor.prototype.clone = function (newObject) {
  65546. if (!newObject)
  65547. return null;
  65548. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65549. };
  65550. PhysicsImpostor.prototype.dispose = function () {
  65551. var _this = this;
  65552. //no dispose if no physics engine is available.
  65553. if (!this._physicsEngine) {
  65554. return;
  65555. }
  65556. this._joints.forEach(function (j) {
  65557. if (_this._physicsEngine) {
  65558. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65559. }
  65560. });
  65561. //dispose the physics body
  65562. this._physicsEngine.removeImpostor(this);
  65563. if (this.parent) {
  65564. this.parent.forceUpdate();
  65565. }
  65566. else {
  65567. /*this._object.getChildMeshes().forEach(function(mesh) {
  65568. if (mesh.physicsImpostor) {
  65569. if (disposeChildren) {
  65570. mesh.physicsImpostor.dispose();
  65571. mesh.physicsImpostor = null;
  65572. }
  65573. }
  65574. })*/
  65575. }
  65576. this._isDisposed = true;
  65577. };
  65578. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65579. this._deltaPosition.copyFrom(position);
  65580. };
  65581. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65582. if (!this._deltaRotation) {
  65583. this._deltaRotation = new BABYLON.Quaternion();
  65584. }
  65585. this._deltaRotation.copyFrom(rotation);
  65586. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65587. };
  65588. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65589. if (this._physicsEngine) {
  65590. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65591. }
  65592. return this;
  65593. };
  65594. PhysicsImpostor.prototype.getRadius = function () {
  65595. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65596. };
  65597. /**
  65598. * Sync a bone with this impostor
  65599. * @param bone The bone to sync to the impostor.
  65600. * @param boneMesh The mesh that the bone is influencing.
  65601. * @param jointPivot The pivot of the joint / bone in local space.
  65602. * @param distToJoint Optional distance from the impostor to the joint.
  65603. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65604. */
  65605. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65606. var tempVec = PhysicsImpostor._tmpVecs[0];
  65607. var mesh = this.object;
  65608. if (mesh.rotationQuaternion) {
  65609. if (adjustRotation) {
  65610. var tempQuat = PhysicsImpostor._tmpQuat;
  65611. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65612. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65613. }
  65614. else {
  65615. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65616. }
  65617. }
  65618. tempVec.x = 0;
  65619. tempVec.y = 0;
  65620. tempVec.z = 0;
  65621. if (jointPivot) {
  65622. tempVec.x = jointPivot.x;
  65623. tempVec.y = jointPivot.y;
  65624. tempVec.z = jointPivot.z;
  65625. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65626. if (distToJoint === undefined || distToJoint === null) {
  65627. distToJoint = jointPivot.length();
  65628. }
  65629. tempVec.x *= distToJoint;
  65630. tempVec.y *= distToJoint;
  65631. tempVec.z *= distToJoint;
  65632. }
  65633. if (bone.getParent()) {
  65634. tempVec.addInPlace(mesh.getAbsolutePosition());
  65635. bone.setAbsolutePosition(tempVec, boneMesh);
  65636. }
  65637. else {
  65638. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65639. boneMesh.position.x -= tempVec.x;
  65640. boneMesh.position.y -= tempVec.y;
  65641. boneMesh.position.z -= tempVec.z;
  65642. }
  65643. };
  65644. /**
  65645. * Sync impostor to a bone
  65646. * @param bone The bone that the impostor will be synced to.
  65647. * @param boneMesh The mesh that the bone is influencing.
  65648. * @param jointPivot The pivot of the joint / bone in local space.
  65649. * @param distToJoint Optional distance from the impostor to the joint.
  65650. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65651. * @param boneAxis Optional vector3 axis the bone is aligned with
  65652. */
  65653. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65654. var mesh = this.object;
  65655. if (mesh.rotationQuaternion) {
  65656. if (adjustRotation) {
  65657. var tempQuat = PhysicsImpostor._tmpQuat;
  65658. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65659. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65660. }
  65661. else {
  65662. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65663. }
  65664. }
  65665. var pos = PhysicsImpostor._tmpVecs[0];
  65666. var boneDir = PhysicsImpostor._tmpVecs[1];
  65667. if (!boneAxis) {
  65668. boneAxis = PhysicsImpostor._tmpVecs[2];
  65669. boneAxis.x = 0;
  65670. boneAxis.y = 1;
  65671. boneAxis.z = 0;
  65672. }
  65673. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65674. bone.getAbsolutePositionToRef(boneMesh, pos);
  65675. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65676. distToJoint = jointPivot.length();
  65677. }
  65678. if (distToJoint !== undefined && distToJoint !== null) {
  65679. pos.x += boneDir.x * distToJoint;
  65680. pos.y += boneDir.y * distToJoint;
  65681. pos.z += boneDir.z * distToJoint;
  65682. }
  65683. mesh.setAbsolutePosition(pos);
  65684. };
  65685. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65686. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65687. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65688. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65689. //Impostor types
  65690. PhysicsImpostor.NoImpostor = 0;
  65691. PhysicsImpostor.SphereImpostor = 1;
  65692. PhysicsImpostor.BoxImpostor = 2;
  65693. PhysicsImpostor.PlaneImpostor = 3;
  65694. PhysicsImpostor.MeshImpostor = 4;
  65695. PhysicsImpostor.CylinderImpostor = 7;
  65696. PhysicsImpostor.ParticleImpostor = 8;
  65697. PhysicsImpostor.HeightmapImpostor = 9;
  65698. return PhysicsImpostor;
  65699. }());
  65700. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65701. })(BABYLON || (BABYLON = {}));
  65702. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65703. var BABYLON;
  65704. (function (BABYLON) {
  65705. var PhysicsEngine = /** @class */ (function () {
  65706. function PhysicsEngine(gravity, _physicsPlugin) {
  65707. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65708. this._physicsPlugin = _physicsPlugin;
  65709. //new methods and parameters
  65710. this._impostors = [];
  65711. this._joints = [];
  65712. if (!this._physicsPlugin.isSupported()) {
  65713. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65714. + "Please make sure it is included.");
  65715. }
  65716. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65717. this.setGravity(gravity);
  65718. this.setTimeStep();
  65719. }
  65720. PhysicsEngine.prototype.setGravity = function (gravity) {
  65721. this.gravity = gravity;
  65722. this._physicsPlugin.setGravity(this.gravity);
  65723. };
  65724. /**
  65725. * Set the time step of the physics engine.
  65726. * default is 1/60.
  65727. * To slow it down, enter 1/600 for example.
  65728. * To speed it up, 1/30
  65729. * @param {number} newTimeStep the new timestep to apply to this world.
  65730. */
  65731. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65732. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65733. this._physicsPlugin.setTimeStep(newTimeStep);
  65734. };
  65735. /**
  65736. * Get the time step of the physics engine.
  65737. */
  65738. PhysicsEngine.prototype.getTimeStep = function () {
  65739. return this._physicsPlugin.getTimeStep();
  65740. };
  65741. PhysicsEngine.prototype.dispose = function () {
  65742. this._impostors.forEach(function (impostor) {
  65743. impostor.dispose();
  65744. });
  65745. this._physicsPlugin.dispose();
  65746. };
  65747. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65748. return this._physicsPlugin.name;
  65749. };
  65750. /**
  65751. * Adding a new impostor for the impostor tracking.
  65752. * This will be done by the impostor itself.
  65753. * @param {PhysicsImpostor} impostor the impostor to add
  65754. */
  65755. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65756. impostor.uniqueId = this._impostors.push(impostor);
  65757. //if no parent, generate the body
  65758. if (!impostor.parent) {
  65759. this._physicsPlugin.generatePhysicsBody(impostor);
  65760. }
  65761. };
  65762. /**
  65763. * Remove an impostor from the engine.
  65764. * This impostor and its mesh will not longer be updated by the physics engine.
  65765. * @param {PhysicsImpostor} impostor the impostor to remove
  65766. */
  65767. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65768. var index = this._impostors.indexOf(impostor);
  65769. if (index > -1) {
  65770. var removed = this._impostors.splice(index, 1);
  65771. //Is it needed?
  65772. if (removed.length) {
  65773. //this will also remove it from the world.
  65774. removed[0].physicsBody = null;
  65775. }
  65776. }
  65777. };
  65778. /**
  65779. * Add a joint to the physics engine
  65780. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65781. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65782. * @param {PhysicsJoint} the joint that will connect both impostors.
  65783. */
  65784. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65785. var impostorJoint = {
  65786. mainImpostor: mainImpostor,
  65787. connectedImpostor: connectedImpostor,
  65788. joint: joint
  65789. };
  65790. joint.physicsPlugin = this._physicsPlugin;
  65791. this._joints.push(impostorJoint);
  65792. this._physicsPlugin.generateJoint(impostorJoint);
  65793. };
  65794. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65795. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65796. return (impostorJoint.connectedImpostor === connectedImpostor
  65797. && impostorJoint.joint === joint
  65798. && impostorJoint.mainImpostor === mainImpostor);
  65799. });
  65800. if (matchingJoints.length) {
  65801. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65802. //TODO remove it from the list as well
  65803. }
  65804. };
  65805. /**
  65806. * Called by the scene. no need to call it.
  65807. */
  65808. PhysicsEngine.prototype._step = function (delta) {
  65809. var _this = this;
  65810. //check if any mesh has no body / requires an update
  65811. this._impostors.forEach(function (impostor) {
  65812. if (impostor.isBodyInitRequired()) {
  65813. _this._physicsPlugin.generatePhysicsBody(impostor);
  65814. }
  65815. });
  65816. if (delta > 0.1) {
  65817. delta = 0.1;
  65818. }
  65819. else if (delta <= 0) {
  65820. delta = 1.0 / 60.0;
  65821. }
  65822. this._physicsPlugin.executeStep(delta, this._impostors);
  65823. };
  65824. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65825. return this._physicsPlugin;
  65826. };
  65827. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65828. for (var i = 0; i < this._impostors.length; ++i) {
  65829. if (this._impostors[i].object === object) {
  65830. return this._impostors[i];
  65831. }
  65832. }
  65833. return null;
  65834. };
  65835. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65836. for (var i = 0; i < this._impostors.length; ++i) {
  65837. if (this._impostors[i].physicsBody === body) {
  65838. return this._impostors[i];
  65839. }
  65840. }
  65841. return null;
  65842. };
  65843. // Statics
  65844. PhysicsEngine.Epsilon = 0.001;
  65845. return PhysicsEngine;
  65846. }());
  65847. BABYLON.PhysicsEngine = PhysicsEngine;
  65848. })(BABYLON || (BABYLON = {}));
  65849. //# sourceMappingURL=babylon.physicsEngine.js.map
  65850. var BABYLON;
  65851. (function (BABYLON) {
  65852. var CannonJSPlugin = /** @class */ (function () {
  65853. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65854. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65855. if (iterations === void 0) { iterations = 10; }
  65856. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65857. this.name = "CannonJSPlugin";
  65858. this._physicsMaterials = new Array();
  65859. this._fixedTimeStep = 1 / 60;
  65860. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65861. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65862. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65863. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65864. this._tmpPosition = BABYLON.Vector3.Zero();
  65865. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65866. this._tmpUnityRotation = new BABYLON.Quaternion();
  65867. if (!this.isSupported()) {
  65868. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65869. return;
  65870. }
  65871. this.world = new this.BJSCANNON.World();
  65872. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65873. this.world.solver.iterations = iterations;
  65874. }
  65875. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65876. this.world.gravity.copy(gravity);
  65877. };
  65878. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65879. this._fixedTimeStep = timeStep;
  65880. };
  65881. CannonJSPlugin.prototype.getTimeStep = function () {
  65882. return this._fixedTimeStep;
  65883. };
  65884. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65885. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65886. };
  65887. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65888. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65889. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65890. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65891. };
  65892. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65893. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65894. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65895. impostor.physicsBody.applyForce(impulse, worldPoint);
  65896. };
  65897. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65898. //parent-child relationship. Does this impostor has a parent impostor?
  65899. if (impostor.parent) {
  65900. if (impostor.physicsBody) {
  65901. this.removePhysicsBody(impostor);
  65902. //TODO is that needed?
  65903. impostor.forceUpdate();
  65904. }
  65905. return;
  65906. }
  65907. //should a new body be created for this impostor?
  65908. if (impostor.isBodyInitRequired()) {
  65909. var shape = this._createShape(impostor);
  65910. //unregister events, if body is being changed
  65911. var oldBody = impostor.physicsBody;
  65912. if (oldBody) {
  65913. this.removePhysicsBody(impostor);
  65914. }
  65915. //create the body and material
  65916. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65917. var bodyCreationObject = {
  65918. mass: impostor.getParam("mass"),
  65919. material: material
  65920. };
  65921. // A simple extend, in case native options were used.
  65922. var nativeOptions = impostor.getParam("nativeOptions");
  65923. for (var key in nativeOptions) {
  65924. if (nativeOptions.hasOwnProperty(key)) {
  65925. bodyCreationObject[key] = nativeOptions[key];
  65926. }
  65927. }
  65928. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65929. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65930. this.world.addEventListener("preStep", impostor.beforeStep);
  65931. this.world.addEventListener("postStep", impostor.afterStep);
  65932. impostor.physicsBody.addShape(shape);
  65933. this.world.add(impostor.physicsBody);
  65934. //try to keep the body moving in the right direction by taking old properties.
  65935. //Should be tested!
  65936. if (oldBody) {
  65937. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65938. impostor.physicsBody[param].copy(oldBody[param]);
  65939. });
  65940. }
  65941. this._processChildMeshes(impostor);
  65942. }
  65943. //now update the body's transformation
  65944. this._updatePhysicsBodyTransformation(impostor);
  65945. };
  65946. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65947. var _this = this;
  65948. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65949. var currentRotation = mainImpostor.object.rotationQuaternion;
  65950. if (meshChildren.length) {
  65951. var processMesh = function (localPosition, mesh) {
  65952. if (!currentRotation || !mesh.rotationQuaternion) {
  65953. return;
  65954. }
  65955. var childImpostor = mesh.getPhysicsImpostor();
  65956. if (childImpostor) {
  65957. var parent = childImpostor.parent;
  65958. if (parent !== mainImpostor) {
  65959. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65960. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65961. if (childImpostor.physicsBody) {
  65962. _this.removePhysicsBody(childImpostor);
  65963. childImpostor.physicsBody = null;
  65964. }
  65965. childImpostor.parent = mainImpostor;
  65966. childImpostor.resetUpdateFlags();
  65967. 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));
  65968. //Add the mass of the children.
  65969. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65970. }
  65971. }
  65972. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65973. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65974. };
  65975. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65976. }
  65977. };
  65978. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65979. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65980. this.world.removeEventListener("preStep", impostor.beforeStep);
  65981. this.world.removeEventListener("postStep", impostor.afterStep);
  65982. this.world.remove(impostor.physicsBody);
  65983. };
  65984. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65985. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65986. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65987. if (!mainBody || !connectedBody) {
  65988. return;
  65989. }
  65990. var constraint;
  65991. var jointData = impostorJoint.joint.jointData;
  65992. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65993. var constraintData = {
  65994. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65995. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65996. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65997. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65998. maxForce: jointData.nativeParams.maxForce,
  65999. collideConnected: !!jointData.collision
  66000. };
  66001. switch (impostorJoint.joint.type) {
  66002. case BABYLON.PhysicsJoint.HingeJoint:
  66003. case BABYLON.PhysicsJoint.Hinge2Joint:
  66004. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  66005. break;
  66006. case BABYLON.PhysicsJoint.DistanceJoint:
  66007. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  66008. break;
  66009. case BABYLON.PhysicsJoint.SpringJoint:
  66010. var springData = jointData;
  66011. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  66012. restLength: springData.length,
  66013. stiffness: springData.stiffness,
  66014. damping: springData.damping,
  66015. localAnchorA: constraintData.pivotA,
  66016. localAnchorB: constraintData.pivotB
  66017. });
  66018. break;
  66019. case BABYLON.PhysicsJoint.LockJoint:
  66020. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  66021. break;
  66022. case BABYLON.PhysicsJoint.PointToPointJoint:
  66023. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66024. default:
  66025. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  66026. break;
  66027. }
  66028. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66029. constraint.collideConnected = !!jointData.collision;
  66030. impostorJoint.joint.physicsJoint = constraint;
  66031. //don't add spring as constraint, as it is not one.
  66032. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66033. this.world.addConstraint(constraint);
  66034. }
  66035. else {
  66036. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66037. constraint.applyForce();
  66038. });
  66039. }
  66040. };
  66041. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66042. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66043. };
  66044. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66045. var index;
  66046. var mat;
  66047. for (index = 0; index < this._physicsMaterials.length; index++) {
  66048. mat = this._physicsMaterials[index];
  66049. if (mat.friction === friction && mat.restitution === restitution) {
  66050. return mat;
  66051. }
  66052. }
  66053. var currentMat = new this.BJSCANNON.Material(name);
  66054. currentMat.friction = friction;
  66055. currentMat.restitution = restitution;
  66056. this._physicsMaterials.push(currentMat);
  66057. return currentMat;
  66058. };
  66059. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66060. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66061. };
  66062. CannonJSPlugin.prototype._createShape = function (impostor) {
  66063. var object = impostor.object;
  66064. var returnValue;
  66065. var extendSize = impostor.getObjectExtendSize();
  66066. switch (impostor.type) {
  66067. case BABYLON.PhysicsImpostor.SphereImpostor:
  66068. var radiusX = extendSize.x;
  66069. var radiusY = extendSize.y;
  66070. var radiusZ = extendSize.z;
  66071. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66072. break;
  66073. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66074. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66075. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66076. break;
  66077. case BABYLON.PhysicsImpostor.BoxImpostor:
  66078. var box = extendSize.scale(0.5);
  66079. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66080. break;
  66081. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66082. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66083. returnValue = new this.BJSCANNON.Plane();
  66084. break;
  66085. case BABYLON.PhysicsImpostor.MeshImpostor:
  66086. // should transform the vertex data to world coordinates!!
  66087. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66088. var rawFaces = object.getIndices ? object.getIndices() : [];
  66089. if (!rawVerts)
  66090. return;
  66091. // get only scale! so the object could transform correctly.
  66092. var oldPosition = object.position.clone();
  66093. var oldRotation = object.rotation && object.rotation.clone();
  66094. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66095. object.position.copyFromFloats(0, 0, 0);
  66096. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66097. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66098. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66099. var transform = object.computeWorldMatrix(true);
  66100. // convert rawVerts to object space
  66101. var temp = new Array();
  66102. var index;
  66103. for (index = 0; index < rawVerts.length; index += 3) {
  66104. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66105. }
  66106. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66107. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66108. //now set back the transformation!
  66109. object.position.copyFrom(oldPosition);
  66110. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66111. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66112. break;
  66113. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66114. var oldPosition2 = object.position.clone();
  66115. var oldRotation2 = object.rotation && object.rotation.clone();
  66116. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  66117. object.position.copyFromFloats(0, 0, 0);
  66118. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66119. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66120. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66121. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  66122. returnValue = this._createHeightmap(object);
  66123. object.position.copyFrom(oldPosition2);
  66124. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  66125. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  66126. object.computeWorldMatrix(true);
  66127. break;
  66128. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66129. returnValue = new this.BJSCANNON.Particle();
  66130. break;
  66131. }
  66132. return returnValue;
  66133. };
  66134. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66135. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66136. var transform = object.computeWorldMatrix(true);
  66137. // convert rawVerts to object space
  66138. var temp = new Array();
  66139. var index;
  66140. for (index = 0; index < pos.length; index += 3) {
  66141. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  66142. }
  66143. pos = temp;
  66144. var matrix = new Array();
  66145. //For now pointDepth will not be used and will be automatically calculated.
  66146. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66147. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66148. var boundingInfo = (object.getBoundingInfo());
  66149. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  66150. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  66151. var elementSize = dim * 2 / arraySize;
  66152. for (var i = 0; i < pos.length; i = i + 3) {
  66153. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66154. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  66155. var y = -pos[i + 2] + minY;
  66156. if (!matrix[x]) {
  66157. matrix[x] = [];
  66158. }
  66159. if (!matrix[x][z]) {
  66160. matrix[x][z] = y;
  66161. }
  66162. matrix[x][z] = Math.max(y, matrix[x][z]);
  66163. }
  66164. for (var x = 0; x <= arraySize; ++x) {
  66165. if (!matrix[x]) {
  66166. var loc = 1;
  66167. while (!matrix[(x + loc) % arraySize]) {
  66168. loc++;
  66169. }
  66170. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66171. //console.log("missing x", x);
  66172. }
  66173. for (var z = 0; z <= arraySize; ++z) {
  66174. if (!matrix[x][z]) {
  66175. var loc = 1;
  66176. var newValue;
  66177. while (newValue === undefined) {
  66178. newValue = matrix[x][(z + loc++) % arraySize];
  66179. }
  66180. matrix[x][z] = newValue;
  66181. }
  66182. }
  66183. }
  66184. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66185. elementSize: elementSize
  66186. });
  66187. //For future reference, needed for body transformation
  66188. shape.minY = minY;
  66189. return shape;
  66190. };
  66191. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66192. var object = impostor.object;
  66193. //make sure it is updated...
  66194. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66195. // The delta between the mesh position and the mesh bounding box center
  66196. var bInfo = object.getBoundingInfo();
  66197. if (!bInfo)
  66198. return;
  66199. var center = impostor.getObjectCenter();
  66200. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66201. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66202. this._tmpPosition.copyFrom(center);
  66203. var quaternion = object.rotationQuaternion;
  66204. if (!quaternion) {
  66205. return;
  66206. }
  66207. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66208. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66209. //-90 DEG in X, precalculated
  66210. quaternion = quaternion.multiply(this._minus90X);
  66211. //Invert! (Precalculated, 90 deg in X)
  66212. //No need to clone. this will never change.
  66213. impostor.setDeltaRotation(this._plus90X);
  66214. }
  66215. //If it is a heightfield, if should be centered.
  66216. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66217. var mesh = object;
  66218. var boundingInfo = mesh.getBoundingInfo();
  66219. //calculate the correct body position:
  66220. var rotationQuaternion = mesh.rotationQuaternion;
  66221. mesh.rotationQuaternion = this._tmpUnityRotation;
  66222. mesh.computeWorldMatrix(true);
  66223. //get original center with no rotation
  66224. var c = center.clone();
  66225. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66226. //rotation is back
  66227. mesh.rotationQuaternion = rotationQuaternion;
  66228. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66229. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66230. mesh.setPivotMatrix(p);
  66231. mesh.computeWorldMatrix(true);
  66232. //calculate the translation
  66233. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66234. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66235. //add it inverted to the delta
  66236. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66237. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66238. mesh.setPivotMatrix(oldPivot);
  66239. mesh.computeWorldMatrix(true);
  66240. }
  66241. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66242. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66243. //this._tmpPosition.copyFrom(object.position);
  66244. }
  66245. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66246. //Now update the impostor object
  66247. impostor.physicsBody.position.copy(this._tmpPosition);
  66248. impostor.physicsBody.quaternion.copy(quaternion);
  66249. };
  66250. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66251. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66252. if (impostor.object.rotationQuaternion) {
  66253. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66254. //impostor.object.rotationQuaternion.y *= -1;
  66255. //impostor.object.rotationQuaternion.z *= -1;
  66256. }
  66257. };
  66258. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66259. impostor.physicsBody.position.copy(newPosition);
  66260. //newRotation.y *= -1;
  66261. //newRotation.z *= -1;
  66262. impostor.physicsBody.quaternion.copy(newRotation);
  66263. };
  66264. CannonJSPlugin.prototype.isSupported = function () {
  66265. return this.BJSCANNON !== undefined;
  66266. };
  66267. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66268. impostor.physicsBody.velocity.copy(velocity);
  66269. };
  66270. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66271. impostor.physicsBody.angularVelocity.copy(velocity);
  66272. };
  66273. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66274. var v = impostor.physicsBody.velocity;
  66275. if (!v) {
  66276. return null;
  66277. }
  66278. return new BABYLON.Vector3(v.x, v.y, v.z);
  66279. };
  66280. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66281. var v = impostor.physicsBody.angularVelocity;
  66282. if (!v) {
  66283. return null;
  66284. }
  66285. return new BABYLON.Vector3(v.x, v.y, v.z);
  66286. };
  66287. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66288. impostor.physicsBody.mass = mass;
  66289. impostor.physicsBody.updateMassProperties();
  66290. };
  66291. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66292. return impostor.physicsBody.mass;
  66293. };
  66294. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66295. return impostor.physicsBody.material.friction;
  66296. };
  66297. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66298. impostor.physicsBody.material.friction = friction;
  66299. };
  66300. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66301. return impostor.physicsBody.material.restitution;
  66302. };
  66303. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66304. impostor.physicsBody.material.restitution = restitution;
  66305. };
  66306. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66307. impostor.physicsBody.sleep();
  66308. };
  66309. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66310. impostor.physicsBody.wakeUp();
  66311. };
  66312. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66313. joint.physicsJoint.distance = maxDistance;
  66314. };
  66315. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66316. // if (!motorIndex) {
  66317. // joint.physicsJoint.enableMotor();
  66318. // }
  66319. // }
  66320. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66321. // if (!motorIndex) {
  66322. // joint.physicsJoint.disableMotor();
  66323. // }
  66324. // }
  66325. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66326. if (!motorIndex) {
  66327. joint.physicsJoint.enableMotor();
  66328. joint.physicsJoint.setMotorSpeed(speed);
  66329. if (maxForce) {
  66330. this.setLimit(joint, maxForce);
  66331. }
  66332. }
  66333. };
  66334. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66335. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66336. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66337. };
  66338. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66339. var body = impostor.physicsBody;
  66340. mesh.position.x = body.position.x;
  66341. mesh.position.y = body.position.y;
  66342. mesh.position.z = body.position.z;
  66343. if (mesh.rotationQuaternion) {
  66344. mesh.rotationQuaternion.x = body.quaternion.x;
  66345. mesh.rotationQuaternion.y = body.quaternion.y;
  66346. mesh.rotationQuaternion.z = body.quaternion.z;
  66347. mesh.rotationQuaternion.w = body.quaternion.w;
  66348. }
  66349. };
  66350. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66351. var shape = impostor.physicsBody.shapes[0];
  66352. return shape.boundingSphereRadius;
  66353. };
  66354. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66355. var shape = impostor.physicsBody.shapes[0];
  66356. result.x = shape.halfExtents.x * 2;
  66357. result.y = shape.halfExtents.y * 2;
  66358. result.z = shape.halfExtents.z * 2;
  66359. };
  66360. CannonJSPlugin.prototype.dispose = function () {
  66361. };
  66362. return CannonJSPlugin;
  66363. }());
  66364. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66365. })(BABYLON || (BABYLON = {}));
  66366. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66367. var BABYLON;
  66368. (function (BABYLON) {
  66369. var OimoJSPlugin = /** @class */ (function () {
  66370. function OimoJSPlugin(iterations) {
  66371. this.name = "OimoJSPlugin";
  66372. this._tmpImpostorsArray = [];
  66373. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66374. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66375. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66376. this.world.worldscale(1);
  66377. this.world.clear();
  66378. //making sure no stats are calculated
  66379. this.world.isNoStat = true;
  66380. }
  66381. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66382. this.world.gravity.copy(gravity);
  66383. };
  66384. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66385. this.world.timeStep = timeStep;
  66386. };
  66387. OimoJSPlugin.prototype.getTimeStep = function () {
  66388. return this.world.timeStep;
  66389. };
  66390. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66391. var _this = this;
  66392. impostors.forEach(function (impostor) {
  66393. impostor.beforeStep();
  66394. });
  66395. this.world.step();
  66396. impostors.forEach(function (impostor) {
  66397. impostor.afterStep();
  66398. //update the ordered impostors array
  66399. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66400. });
  66401. //check for collisions
  66402. var contact = this.world.contacts;
  66403. while (contact !== null) {
  66404. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66405. contact = contact.next;
  66406. continue;
  66407. }
  66408. //is this body colliding with any other? get the impostor
  66409. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66410. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66411. if (!mainImpostor || !collidingImpostor) {
  66412. contact = contact.next;
  66413. continue;
  66414. }
  66415. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66416. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66417. contact = contact.next;
  66418. }
  66419. };
  66420. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66421. var mass = impostor.physicsBody.massInfo.mass;
  66422. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66423. };
  66424. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66425. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66426. this.applyImpulse(impostor, force, contactPoint);
  66427. };
  66428. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66429. var _this = this;
  66430. //parent-child relationship. Does this impostor has a parent impostor?
  66431. if (impostor.parent) {
  66432. if (impostor.physicsBody) {
  66433. this.removePhysicsBody(impostor);
  66434. //TODO is that needed?
  66435. impostor.forceUpdate();
  66436. }
  66437. return;
  66438. }
  66439. if (impostor.isBodyInitRequired()) {
  66440. var bodyConfig = {
  66441. name: impostor.uniqueId,
  66442. //Oimo must have mass, also for static objects.
  66443. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66444. size: [],
  66445. type: [],
  66446. pos: [],
  66447. rot: [],
  66448. move: impostor.getParam("mass") !== 0,
  66449. //Supporting older versions of Oimo
  66450. world: this.world
  66451. };
  66452. var impostors = [impostor];
  66453. var addToArray = function (parent) {
  66454. if (!parent.getChildMeshes)
  66455. return;
  66456. parent.getChildMeshes().forEach(function (m) {
  66457. if (m.physicsImpostor) {
  66458. impostors.push(m.physicsImpostor);
  66459. //m.physicsImpostor._init();
  66460. }
  66461. });
  66462. };
  66463. addToArray(impostor.object);
  66464. var checkWithEpsilon_1 = function (value) {
  66465. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66466. };
  66467. impostors.forEach(function (i) {
  66468. if (!impostor.object.rotationQuaternion) {
  66469. return;
  66470. }
  66471. //get the correct bounding box
  66472. var oldQuaternion = i.object.rotationQuaternion;
  66473. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66474. x: impostor.object.rotationQuaternion.x,
  66475. y: impostor.object.rotationQuaternion.y,
  66476. z: impostor.object.rotationQuaternion.z,
  66477. s: impostor.object.rotationQuaternion.w
  66478. });
  66479. var extendSize = i.getObjectExtendSize();
  66480. if (i === impostor) {
  66481. var center = impostor.getObjectCenter();
  66482. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66483. //Can also use Array.prototype.push.apply
  66484. bodyConfig.pos.push(center.x);
  66485. bodyConfig.pos.push(center.y);
  66486. bodyConfig.pos.push(center.z);
  66487. //tmp solution
  66488. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66489. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66490. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66491. }
  66492. else {
  66493. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66494. bodyConfig.pos.push(localPosition.x);
  66495. bodyConfig.pos.push(localPosition.y);
  66496. bodyConfig.pos.push(localPosition.z);
  66497. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66498. bodyConfig.rot.push(0);
  66499. bodyConfig.rot.push(0);
  66500. bodyConfig.rot.push(0);
  66501. }
  66502. // register mesh
  66503. switch (i.type) {
  66504. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66505. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66506. case BABYLON.PhysicsImpostor.SphereImpostor:
  66507. var radiusX = extendSize.x;
  66508. var radiusY = extendSize.y;
  66509. var radiusZ = extendSize.z;
  66510. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66511. bodyConfig.type.push('sphere');
  66512. //due to the way oimo works with compounds, add 3 times
  66513. bodyConfig.size.push(size);
  66514. bodyConfig.size.push(size);
  66515. bodyConfig.size.push(size);
  66516. break;
  66517. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66518. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66519. var sizeY = checkWithEpsilon_1(extendSize.y);
  66520. bodyConfig.type.push('cylinder');
  66521. bodyConfig.size.push(sizeX);
  66522. bodyConfig.size.push(sizeY);
  66523. //due to the way oimo works with compounds, add one more value.
  66524. bodyConfig.size.push(sizeY);
  66525. break;
  66526. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66527. case BABYLON.PhysicsImpostor.BoxImpostor:
  66528. default:
  66529. var sizeX = checkWithEpsilon_1(extendSize.x);
  66530. var sizeY = checkWithEpsilon_1(extendSize.y);
  66531. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66532. bodyConfig.type.push('box');
  66533. bodyConfig.size.push(sizeX);
  66534. bodyConfig.size.push(sizeY);
  66535. bodyConfig.size.push(sizeZ);
  66536. break;
  66537. }
  66538. //actually not needed, but hey...
  66539. i.object.rotationQuaternion = oldQuaternion;
  66540. });
  66541. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66542. }
  66543. else {
  66544. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66545. }
  66546. impostor.setDeltaPosition(this._tmpPositionVector);
  66547. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66548. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66549. };
  66550. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66551. //impostor.physicsBody.dispose();
  66552. //Same as : (older oimo versions)
  66553. this.world.removeRigidBody(impostor.physicsBody);
  66554. };
  66555. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66556. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66557. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66558. if (!mainBody || !connectedBody) {
  66559. return;
  66560. }
  66561. var jointData = impostorJoint.joint.jointData;
  66562. var options = jointData.nativeParams || {};
  66563. var type;
  66564. var nativeJointData = {
  66565. body1: mainBody,
  66566. body2: connectedBody,
  66567. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66568. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66569. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66570. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66571. min: options.min,
  66572. max: options.max,
  66573. collision: options.collision || jointData.collision,
  66574. spring: options.spring,
  66575. //supporting older version of Oimo
  66576. world: this.world
  66577. };
  66578. switch (impostorJoint.joint.type) {
  66579. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66580. type = "jointBall";
  66581. break;
  66582. case BABYLON.PhysicsJoint.SpringJoint:
  66583. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66584. var springData = jointData;
  66585. nativeJointData.min = springData.length || nativeJointData.min;
  66586. //Max should also be set, just make sure it is at least min
  66587. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66588. case BABYLON.PhysicsJoint.DistanceJoint:
  66589. type = "jointDistance";
  66590. nativeJointData.max = jointData.maxDistance;
  66591. break;
  66592. case BABYLON.PhysicsJoint.PrismaticJoint:
  66593. type = "jointPrisme";
  66594. break;
  66595. case BABYLON.PhysicsJoint.SliderJoint:
  66596. type = "jointSlide";
  66597. break;
  66598. case BABYLON.PhysicsJoint.WheelJoint:
  66599. type = "jointWheel";
  66600. break;
  66601. case BABYLON.PhysicsJoint.HingeJoint:
  66602. default:
  66603. type = "jointHinge";
  66604. break;
  66605. }
  66606. nativeJointData.type = type;
  66607. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66608. };
  66609. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66610. //Bug in Oimo prevents us from disposing a joint in the playground
  66611. //joint.joint.physicsJoint.dispose();
  66612. //So we will bruteforce it!
  66613. try {
  66614. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66615. }
  66616. catch (e) {
  66617. BABYLON.Tools.Warn(e);
  66618. }
  66619. };
  66620. OimoJSPlugin.prototype.isSupported = function () {
  66621. return this.BJSOIMO !== undefined;
  66622. };
  66623. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66624. if (!impostor.physicsBody.sleeping) {
  66625. //TODO check that
  66626. if (impostor.physicsBody.shapes.next) {
  66627. var parentShape = this._getLastShape(impostor.physicsBody);
  66628. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66629. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66630. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66631. }
  66632. else {
  66633. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66634. }
  66635. if (impostor.object.rotationQuaternion) {
  66636. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66637. impostor.object.rotationQuaternion.normalize();
  66638. }
  66639. }
  66640. };
  66641. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66642. var body = impostor.physicsBody;
  66643. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66644. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66645. body.syncShapes();
  66646. body.awake();
  66647. };
  66648. OimoJSPlugin.prototype._getLastShape = function (body) {
  66649. var lastShape = body.shapes;
  66650. while (lastShape.next) {
  66651. lastShape = lastShape.next;
  66652. }
  66653. return lastShape;
  66654. };
  66655. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66656. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66657. };
  66658. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66659. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66660. };
  66661. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66662. var v = impostor.physicsBody.linearVelocity;
  66663. if (!v) {
  66664. return null;
  66665. }
  66666. return new BABYLON.Vector3(v.x, v.y, v.z);
  66667. };
  66668. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66669. var v = impostor.physicsBody.angularVelocity;
  66670. if (!v) {
  66671. return null;
  66672. }
  66673. return new BABYLON.Vector3(v.x, v.y, v.z);
  66674. };
  66675. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66676. var staticBody = mass === 0;
  66677. //this will actually set the body's density and not its mass.
  66678. //But this is how oimo treats the mass variable.
  66679. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66680. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66681. };
  66682. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66683. return impostor.physicsBody.shapes.density;
  66684. };
  66685. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66686. return impostor.physicsBody.shapes.friction;
  66687. };
  66688. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66689. impostor.physicsBody.shapes.friction = friction;
  66690. };
  66691. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66692. return impostor.physicsBody.shapes.restitution;
  66693. };
  66694. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66695. impostor.physicsBody.shapes.restitution = restitution;
  66696. };
  66697. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66698. impostor.physicsBody.sleep();
  66699. };
  66700. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66701. impostor.physicsBody.awake();
  66702. };
  66703. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66704. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66705. if (minDistance !== void 0) {
  66706. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66707. }
  66708. };
  66709. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66710. //TODO separate rotational and transational motors.
  66711. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66712. if (motor) {
  66713. motor.setMotor(speed, maxForce);
  66714. }
  66715. };
  66716. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66717. //TODO separate rotational and transational motors.
  66718. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66719. if (motor) {
  66720. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66721. }
  66722. };
  66723. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66724. var body = impostor.physicsBody;
  66725. mesh.position.x = body.position.x;
  66726. mesh.position.y = body.position.y;
  66727. mesh.position.z = body.position.z;
  66728. if (mesh.rotationQuaternion) {
  66729. mesh.rotationQuaternion.x = body.orientation.x;
  66730. mesh.rotationQuaternion.y = body.orientation.y;
  66731. mesh.rotationQuaternion.z = body.orientation.z;
  66732. mesh.rotationQuaternion.w = body.orientation.s;
  66733. }
  66734. };
  66735. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66736. return impostor.physicsBody.shapes.radius;
  66737. };
  66738. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66739. var shape = impostor.physicsBody.shapes;
  66740. result.x = shape.halfWidth * 2;
  66741. result.y = shape.halfHeight * 2;
  66742. result.z = shape.halfDepth * 2;
  66743. };
  66744. OimoJSPlugin.prototype.dispose = function () {
  66745. this.world.clear();
  66746. };
  66747. return OimoJSPlugin;
  66748. }());
  66749. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66750. })(BABYLON || (BABYLON = {}));
  66751. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66752. var BABYLON;
  66753. (function (BABYLON) {
  66754. var Internals;
  66755. (function (Internals) {
  66756. /*
  66757. * Based on jsTGALoader - Javascript loader for TGA file
  66758. * By Vincent Thibault
  66759. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66760. */
  66761. var TGATools = /** @class */ (function () {
  66762. function TGATools() {
  66763. }
  66764. TGATools.GetTGAHeader = function (data) {
  66765. var offset = 0;
  66766. var header = {
  66767. id_length: data[offset++],
  66768. colormap_type: data[offset++],
  66769. image_type: data[offset++],
  66770. colormap_index: data[offset++] | data[offset++] << 8,
  66771. colormap_length: data[offset++] | data[offset++] << 8,
  66772. colormap_size: data[offset++],
  66773. origin: [
  66774. data[offset++] | data[offset++] << 8,
  66775. data[offset++] | data[offset++] << 8
  66776. ],
  66777. width: data[offset++] | data[offset++] << 8,
  66778. height: data[offset++] | data[offset++] << 8,
  66779. pixel_size: data[offset++],
  66780. flags: data[offset++]
  66781. };
  66782. return header;
  66783. };
  66784. TGATools.UploadContent = function (gl, data) {
  66785. // Not enough data to contain header ?
  66786. if (data.length < 19) {
  66787. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66788. return;
  66789. }
  66790. // Read Header
  66791. var offset = 18;
  66792. var header = TGATools.GetTGAHeader(data);
  66793. // Assume it's a valid Targa file.
  66794. if (header.id_length + offset > data.length) {
  66795. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66796. return;
  66797. }
  66798. // Skip not needed data
  66799. offset += header.id_length;
  66800. var use_rle = false;
  66801. var use_pal = false;
  66802. var use_rgb = false;
  66803. var use_grey = false;
  66804. // Get some informations.
  66805. switch (header.image_type) {
  66806. case TGATools._TYPE_RLE_INDEXED:
  66807. use_rle = true;
  66808. case TGATools._TYPE_INDEXED:
  66809. use_pal = true;
  66810. break;
  66811. case TGATools._TYPE_RLE_RGB:
  66812. use_rle = true;
  66813. case TGATools._TYPE_RGB:
  66814. use_rgb = true;
  66815. break;
  66816. case TGATools._TYPE_RLE_GREY:
  66817. use_rle = true;
  66818. case TGATools._TYPE_GREY:
  66819. use_grey = true;
  66820. break;
  66821. }
  66822. var pixel_data;
  66823. // var numAlphaBits = header.flags & 0xf;
  66824. var pixel_size = header.pixel_size >> 3;
  66825. var pixel_total = header.width * header.height * pixel_size;
  66826. // Read palettes
  66827. var palettes;
  66828. if (use_pal) {
  66829. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66830. }
  66831. // Read LRE
  66832. if (use_rle) {
  66833. pixel_data = new Uint8Array(pixel_total);
  66834. var c, count, i;
  66835. var localOffset = 0;
  66836. var pixels = new Uint8Array(pixel_size);
  66837. while (offset < pixel_total && localOffset < pixel_total) {
  66838. c = data[offset++];
  66839. count = (c & 0x7f) + 1;
  66840. // RLE pixels
  66841. if (c & 0x80) {
  66842. // Bind pixel tmp array
  66843. for (i = 0; i < pixel_size; ++i) {
  66844. pixels[i] = data[offset++];
  66845. }
  66846. // Copy pixel array
  66847. for (i = 0; i < count; ++i) {
  66848. pixel_data.set(pixels, localOffset + i * pixel_size);
  66849. }
  66850. localOffset += pixel_size * count;
  66851. }
  66852. else {
  66853. count *= pixel_size;
  66854. for (i = 0; i < count; ++i) {
  66855. pixel_data[localOffset + i] = data[offset++];
  66856. }
  66857. localOffset += count;
  66858. }
  66859. }
  66860. }
  66861. else {
  66862. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66863. }
  66864. // Load to texture
  66865. var x_start, y_start, x_step, y_step, y_end, x_end;
  66866. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66867. default:
  66868. case TGATools._ORIGIN_UL:
  66869. x_start = 0;
  66870. x_step = 1;
  66871. x_end = header.width;
  66872. y_start = 0;
  66873. y_step = 1;
  66874. y_end = header.height;
  66875. break;
  66876. case TGATools._ORIGIN_BL:
  66877. x_start = 0;
  66878. x_step = 1;
  66879. x_end = header.width;
  66880. y_start = header.height - 1;
  66881. y_step = -1;
  66882. y_end = -1;
  66883. break;
  66884. case TGATools._ORIGIN_UR:
  66885. x_start = header.width - 1;
  66886. x_step = -1;
  66887. x_end = -1;
  66888. y_start = 0;
  66889. y_step = 1;
  66890. y_end = header.height;
  66891. break;
  66892. case TGATools._ORIGIN_BR:
  66893. x_start = header.width - 1;
  66894. x_step = -1;
  66895. x_end = -1;
  66896. y_start = header.height - 1;
  66897. y_step = -1;
  66898. y_end = -1;
  66899. break;
  66900. }
  66901. // Load the specify method
  66902. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66903. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66904. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66905. };
  66906. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66907. var image = pixel_data, colormap = palettes;
  66908. var width = header.width, height = header.height;
  66909. var color, i = 0, x, y;
  66910. var imageData = new Uint8Array(width * height * 4);
  66911. for (y = y_start; y !== y_end; y += y_step) {
  66912. for (x = x_start; x !== x_end; x += x_step, i++) {
  66913. color = image[i];
  66914. imageData[(x + width * y) * 4 + 3] = 255;
  66915. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66916. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66917. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66918. }
  66919. }
  66920. return imageData;
  66921. };
  66922. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66923. var image = pixel_data;
  66924. var width = header.width, height = header.height;
  66925. var color, i = 0, x, y;
  66926. var imageData = new Uint8Array(width * height * 4);
  66927. for (y = y_start; y !== y_end; y += y_step) {
  66928. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66929. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66930. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66931. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66932. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66933. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66934. }
  66935. }
  66936. return imageData;
  66937. };
  66938. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66939. var image = pixel_data;
  66940. var width = header.width, height = header.height;
  66941. var i = 0, x, y;
  66942. var imageData = new Uint8Array(width * height * 4);
  66943. for (y = y_start; y !== y_end; y += y_step) {
  66944. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66945. imageData[(x + width * y) * 4 + 3] = 255;
  66946. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66947. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66948. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66949. }
  66950. }
  66951. return imageData;
  66952. };
  66953. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66954. var image = pixel_data;
  66955. var width = header.width, height = header.height;
  66956. var i = 0, x, y;
  66957. var imageData = new Uint8Array(width * height * 4);
  66958. for (y = y_start; y !== y_end; y += y_step) {
  66959. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66960. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66961. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66962. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66963. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66964. }
  66965. }
  66966. return imageData;
  66967. };
  66968. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66969. var image = pixel_data;
  66970. var width = header.width, height = header.height;
  66971. var color, i = 0, x, y;
  66972. var imageData = new Uint8Array(width * height * 4);
  66973. for (y = y_start; y !== y_end; y += y_step) {
  66974. for (x = x_start; x !== x_end; x += x_step, i++) {
  66975. color = image[i];
  66976. imageData[(x + width * y) * 4 + 0] = color;
  66977. imageData[(x + width * y) * 4 + 1] = color;
  66978. imageData[(x + width * y) * 4 + 2] = color;
  66979. imageData[(x + width * y) * 4 + 3] = 255;
  66980. }
  66981. }
  66982. return imageData;
  66983. };
  66984. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66985. var image = pixel_data;
  66986. var width = header.width, height = header.height;
  66987. var i = 0, x, y;
  66988. var imageData = new Uint8Array(width * height * 4);
  66989. for (y = y_start; y !== y_end; y += y_step) {
  66990. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66991. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66992. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66993. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66994. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66995. }
  66996. }
  66997. return imageData;
  66998. };
  66999. //private static _TYPE_NO_DATA = 0;
  67000. TGATools._TYPE_INDEXED = 1;
  67001. TGATools._TYPE_RGB = 2;
  67002. TGATools._TYPE_GREY = 3;
  67003. TGATools._TYPE_RLE_INDEXED = 9;
  67004. TGATools._TYPE_RLE_RGB = 10;
  67005. TGATools._TYPE_RLE_GREY = 11;
  67006. TGATools._ORIGIN_MASK = 0x30;
  67007. TGATools._ORIGIN_SHIFT = 0x04;
  67008. TGATools._ORIGIN_BL = 0x00;
  67009. TGATools._ORIGIN_BR = 0x01;
  67010. TGATools._ORIGIN_UL = 0x02;
  67011. TGATools._ORIGIN_UR = 0x03;
  67012. return TGATools;
  67013. }());
  67014. Internals.TGATools = TGATools;
  67015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67016. })(BABYLON || (BABYLON = {}));
  67017. //# sourceMappingURL=babylon.tga.js.map
  67018. var BABYLON;
  67019. (function (BABYLON) {
  67020. var Internals;
  67021. (function (Internals) {
  67022. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  67023. // All values and structures referenced from:
  67024. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  67025. var DDS_MAGIC = 0x20534444;
  67026. var
  67027. //DDSD_CAPS = 0x1,
  67028. //DDSD_HEIGHT = 0x2,
  67029. //DDSD_WIDTH = 0x4,
  67030. //DDSD_PITCH = 0x8,
  67031. //DDSD_PIXELFORMAT = 0x1000,
  67032. DDSD_MIPMAPCOUNT = 0x20000;
  67033. //DDSD_LINEARSIZE = 0x80000,
  67034. //DDSD_DEPTH = 0x800000;
  67035. // var DDSCAPS_COMPLEX = 0x8,
  67036. // DDSCAPS_MIPMAP = 0x400000,
  67037. // DDSCAPS_TEXTURE = 0x1000;
  67038. var DDSCAPS2_CUBEMAP = 0x200;
  67039. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  67040. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  67041. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  67042. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  67043. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  67044. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  67045. // DDSCAPS2_VOLUME = 0x200000;
  67046. var
  67047. //DDPF_ALPHAPIXELS = 0x1,
  67048. //DDPF_ALPHA = 0x2,
  67049. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67050. //DDPF_YUV = 0x200,
  67051. DDPF_LUMINANCE = 0x20000;
  67052. function FourCCToInt32(value) {
  67053. return value.charCodeAt(0) +
  67054. (value.charCodeAt(1) << 8) +
  67055. (value.charCodeAt(2) << 16) +
  67056. (value.charCodeAt(3) << 24);
  67057. }
  67058. function Int32ToFourCC(value) {
  67059. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67060. }
  67061. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67062. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67063. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67064. var FOURCC_DX10 = FourCCToInt32("DX10");
  67065. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67066. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67067. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67068. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67069. var headerLengthInt = 31; // The header length in 32 bit ints
  67070. // Offsets into the header array
  67071. var off_magic = 0;
  67072. var off_size = 1;
  67073. var off_flags = 2;
  67074. var off_height = 3;
  67075. var off_width = 4;
  67076. var off_mipmapCount = 7;
  67077. var off_pfFlags = 20;
  67078. var off_pfFourCC = 21;
  67079. var off_RGBbpp = 22;
  67080. // var off_RMask = 23;
  67081. // var off_GMask = 24;
  67082. // var off_BMask = 25;
  67083. // var off_AMask = 26;
  67084. // var off_caps1 = 27;
  67085. var off_caps2 = 28;
  67086. // var off_caps3 = 29;
  67087. // var off_caps4 = 30;
  67088. var off_dxgiFormat = 32;
  67089. ;
  67090. var DDSTools = /** @class */ (function () {
  67091. function DDSTools() {
  67092. }
  67093. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67094. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67095. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67096. var mipmapCount = 1;
  67097. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67098. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67099. }
  67100. var fourCC = header[off_pfFourCC];
  67101. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67102. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67103. switch (fourCC) {
  67104. case FOURCC_D3DFMT_R16G16B16A16F:
  67105. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67106. break;
  67107. case FOURCC_D3DFMT_R32G32B32A32F:
  67108. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67109. break;
  67110. case FOURCC_DX10:
  67111. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67112. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67113. break;
  67114. }
  67115. }
  67116. return {
  67117. width: header[off_width],
  67118. height: header[off_height],
  67119. mipmapCount: mipmapCount,
  67120. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67121. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67122. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67123. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67124. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  67125. dxgiFormat: dxgiFormat,
  67126. textureType: textureType
  67127. };
  67128. };
  67129. DDSTools._ToHalfFloat = function (value) {
  67130. if (!DDSTools._FloatView) {
  67131. DDSTools._FloatView = new Float32Array(1);
  67132. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67133. }
  67134. DDSTools._FloatView[0] = value;
  67135. var x = DDSTools._Int32View[0];
  67136. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67137. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67138. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67139. /* If zero, or denormal, or exponent underflows too much for a denormal
  67140. * half, return signed zero. */
  67141. if (e < 103) {
  67142. return bits;
  67143. }
  67144. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67145. if (e > 142) {
  67146. bits |= 0x7c00;
  67147. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67148. * not Inf, so make sure we set one mantissa bit too. */
  67149. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67150. return bits;
  67151. }
  67152. /* If exponent underflows but not too much, return a denormal */
  67153. if (e < 113) {
  67154. m |= 0x0800;
  67155. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67156. * to 1, which is OK. */
  67157. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67158. return bits;
  67159. }
  67160. bits |= ((e - 112) << 10) | (m >> 1);
  67161. bits += m & 1;
  67162. return bits;
  67163. };
  67164. DDSTools._FromHalfFloat = function (value) {
  67165. var s = (value & 0x8000) >> 15;
  67166. var e = (value & 0x7C00) >> 10;
  67167. var f = value & 0x03FF;
  67168. if (e === 0) {
  67169. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67170. }
  67171. else if (e == 0x1F) {
  67172. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67173. }
  67174. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67175. };
  67176. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67177. var destArray = new Float32Array(dataLength);
  67178. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67179. var index = 0;
  67180. for (var y = 0; y < height; y++) {
  67181. for (var x = 0; x < width; x++) {
  67182. var srcPos = (x + y * width) * 4;
  67183. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67184. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67185. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67186. if (DDSTools.StoreLODInAlphaChannel) {
  67187. destArray[index + 3] = lod;
  67188. }
  67189. else {
  67190. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67191. }
  67192. index += 4;
  67193. }
  67194. }
  67195. return destArray;
  67196. };
  67197. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67198. if (DDSTools.StoreLODInAlphaChannel) {
  67199. var destArray = new Uint16Array(dataLength);
  67200. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67201. var index = 0;
  67202. for (var y = 0; y < height; y++) {
  67203. for (var x = 0; x < width; x++) {
  67204. var srcPos = (x + y * width) * 4;
  67205. destArray[index] = srcData[srcPos];
  67206. destArray[index + 1] = srcData[srcPos + 1];
  67207. destArray[index + 2] = srcData[srcPos + 2];
  67208. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67209. index += 4;
  67210. }
  67211. }
  67212. return destArray;
  67213. }
  67214. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67215. };
  67216. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67217. if (DDSTools.StoreLODInAlphaChannel) {
  67218. var destArray = new Float32Array(dataLength);
  67219. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67220. var index = 0;
  67221. for (var y = 0; y < height; y++) {
  67222. for (var x = 0; x < width; x++) {
  67223. var srcPos = (x + y * width) * 4;
  67224. destArray[index] = srcData[srcPos];
  67225. destArray[index + 1] = srcData[srcPos + 1];
  67226. destArray[index + 2] = srcData[srcPos + 2];
  67227. destArray[index + 3] = lod;
  67228. index += 4;
  67229. }
  67230. }
  67231. return destArray;
  67232. }
  67233. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67234. };
  67235. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67236. var destArray = new Uint8Array(dataLength);
  67237. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67238. var index = 0;
  67239. for (var y = 0; y < height; y++) {
  67240. for (var x = 0; x < width; x++) {
  67241. var srcPos = (x + y * width) * 4;
  67242. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67243. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67244. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67245. if (DDSTools.StoreLODInAlphaChannel) {
  67246. destArray[index + 3] = lod;
  67247. }
  67248. else {
  67249. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67250. }
  67251. index += 4;
  67252. }
  67253. }
  67254. return destArray;
  67255. };
  67256. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67257. var destArray = new Uint8Array(dataLength);
  67258. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67259. var index = 0;
  67260. for (var y = 0; y < height; y++) {
  67261. for (var x = 0; x < width; x++) {
  67262. var srcPos = (x + y * width) * 4;
  67263. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67264. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67265. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67266. if (DDSTools.StoreLODInAlphaChannel) {
  67267. destArray[index + 3] = lod;
  67268. }
  67269. else {
  67270. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67271. }
  67272. index += 4;
  67273. }
  67274. }
  67275. return destArray;
  67276. };
  67277. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67278. var byteArray = new Uint8Array(dataLength);
  67279. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67280. var index = 0;
  67281. for (var y = 0; y < height; y++) {
  67282. for (var x = 0; x < width; x++) {
  67283. var srcPos = (x + y * width) * 4;
  67284. byteArray[index] = srcData[srcPos + 2];
  67285. byteArray[index + 1] = srcData[srcPos + 1];
  67286. byteArray[index + 2] = srcData[srcPos];
  67287. byteArray[index + 3] = srcData[srcPos + 3];
  67288. index += 4;
  67289. }
  67290. }
  67291. return byteArray;
  67292. };
  67293. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67294. var byteArray = new Uint8Array(dataLength);
  67295. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67296. var index = 0;
  67297. for (var y = 0; y < height; y++) {
  67298. for (var x = 0; x < width; x++) {
  67299. var srcPos = (x + y * width) * 3;
  67300. byteArray[index] = srcData[srcPos + 2];
  67301. byteArray[index + 1] = srcData[srcPos + 1];
  67302. byteArray[index + 2] = srcData[srcPos];
  67303. index += 3;
  67304. }
  67305. }
  67306. return byteArray;
  67307. };
  67308. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67309. var byteArray = new Uint8Array(dataLength);
  67310. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67311. var index = 0;
  67312. for (var y = 0; y < height; y++) {
  67313. for (var x = 0; x < width; x++) {
  67314. var srcPos = (x + y * width);
  67315. byteArray[index] = srcData[srcPos];
  67316. index++;
  67317. }
  67318. }
  67319. return byteArray;
  67320. };
  67321. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67322. if (lodIndex === void 0) { lodIndex = -1; }
  67323. var ext = engine.getCaps().s3tc;
  67324. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67325. var internalFormat = 0;
  67326. var format = 0;
  67327. var blockBytes = 1;
  67328. if (header[off_magic] != DDS_MAGIC) {
  67329. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67330. return;
  67331. }
  67332. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67333. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67334. return;
  67335. }
  67336. if (info.isCompressed && !ext) {
  67337. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67338. return;
  67339. }
  67340. var bpp = header[off_RGBbpp];
  67341. dataOffset = header[off_size] + 4;
  67342. var computeFormats = false;
  67343. if (info.isFourCC) {
  67344. fourCC = header[off_pfFourCC];
  67345. switch (fourCC) {
  67346. case FOURCC_DXT1:
  67347. blockBytes = 8;
  67348. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67349. break;
  67350. case FOURCC_DXT3:
  67351. blockBytes = 16;
  67352. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67353. break;
  67354. case FOURCC_DXT5:
  67355. blockBytes = 16;
  67356. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67357. break;
  67358. case FOURCC_D3DFMT_R16G16B16A16F:
  67359. computeFormats = true;
  67360. break;
  67361. case FOURCC_D3DFMT_R32G32B32A32F:
  67362. computeFormats = true;
  67363. break;
  67364. case FOURCC_DX10:
  67365. // There is an additionnal header so dataOffset need to be changed
  67366. dataOffset += 5 * 4; // 5 uints
  67367. var supported = false;
  67368. switch (info.dxgiFormat) {
  67369. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67370. computeFormats = true;
  67371. supported = true;
  67372. break;
  67373. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67374. info.isRGB = true;
  67375. info.isFourCC = false;
  67376. bpp = 32;
  67377. supported = true;
  67378. break;
  67379. }
  67380. if (supported) {
  67381. break;
  67382. }
  67383. default:
  67384. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67385. return;
  67386. }
  67387. }
  67388. if (computeFormats) {
  67389. format = engine._getWebGLTextureType(info.textureType);
  67390. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67391. }
  67392. mipmapCount = 1;
  67393. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67394. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67395. }
  67396. for (var face = 0; face < faces; face++) {
  67397. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67398. width = header[off_width];
  67399. height = header[off_height];
  67400. for (mip = 0; mip < mipmapCount; ++mip) {
  67401. if (lodIndex === -1 || lodIndex === mip) {
  67402. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67403. var i = (lodIndex === -1) ? mip : 0;
  67404. if (!info.isCompressed && info.isFourCC) {
  67405. dataLength = width * height * 4;
  67406. var FloatArray = null;
  67407. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67408. if (bpp === 128) {
  67409. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67410. }
  67411. else if (bpp === 64) {
  67412. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67413. }
  67414. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67415. format = engine._getWebGLTextureType(info.textureType);
  67416. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67417. }
  67418. else {
  67419. if (bpp === 128) {
  67420. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67421. }
  67422. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67423. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67424. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67425. format = engine._getWebGLTextureType(info.textureType);
  67426. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67427. }
  67428. else {
  67429. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67430. }
  67431. }
  67432. if (FloatArray) {
  67433. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67434. }
  67435. }
  67436. else if (info.isRGB) {
  67437. if (bpp === 24) {
  67438. dataLength = width * height * 3;
  67439. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67440. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67441. }
  67442. else {
  67443. dataLength = width * height * 4;
  67444. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67445. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67446. }
  67447. }
  67448. else if (info.isLuminance) {
  67449. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67450. var unpaddedRowSize = width;
  67451. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67452. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67453. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67454. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67455. }
  67456. else {
  67457. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67458. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67459. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67460. }
  67461. }
  67462. dataOffset += width * height * (bpp / 8);
  67463. width *= 0.5;
  67464. height *= 0.5;
  67465. width = Math.max(1.0, width);
  67466. height = Math.max(1.0, height);
  67467. }
  67468. }
  67469. };
  67470. DDSTools.StoreLODInAlphaChannel = false;
  67471. return DDSTools;
  67472. }());
  67473. Internals.DDSTools = DDSTools;
  67474. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67475. })(BABYLON || (BABYLON = {}));
  67476. //# sourceMappingURL=babylon.dds.js.map
  67477. var BABYLON;
  67478. (function (BABYLON) {
  67479. var Internals;
  67480. (function (Internals) {
  67481. /**
  67482. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67483. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67484. */
  67485. var KhronosTextureContainer = /** @class */ (function () {
  67486. /**
  67487. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67488. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67489. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67490. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67491. */
  67492. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67493. this.arrayBuffer = arrayBuffer;
  67494. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67495. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67496. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67497. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67498. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67499. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67500. BABYLON.Tools.Error("texture missing KTX identifier");
  67501. return;
  67502. }
  67503. // load the reset of the header in native 32 bit int
  67504. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67505. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67506. var oppositeEndianess = header[0] === 0x01020304;
  67507. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67508. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67509. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67510. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67511. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67512. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67513. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67514. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67515. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67516. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67517. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67518. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67519. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67520. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67521. if (this.glType !== 0) {
  67522. BABYLON.Tools.Error("only compressed formats currently supported");
  67523. return;
  67524. }
  67525. else {
  67526. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67527. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67528. }
  67529. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67530. BABYLON.Tools.Error("only 2D textures currently supported");
  67531. return;
  67532. }
  67533. if (this.numberOfArrayElements !== 0) {
  67534. BABYLON.Tools.Error("texture arrays not currently supported");
  67535. return;
  67536. }
  67537. if (this.numberOfFaces !== facesExpected) {
  67538. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67539. return;
  67540. }
  67541. // we now have a completely validated file, so could use existence of loadType as success
  67542. // would need to make this more elaborate & adjust checks above to support more than one load type
  67543. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67544. }
  67545. // not as fast hardware based, but will probably never need to use
  67546. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67547. return ((val & 0xFF) << 24)
  67548. | ((val & 0xFF00) << 8)
  67549. | ((val >> 8) & 0xFF00)
  67550. | ((val >> 24) & 0xFF);
  67551. };
  67552. /**
  67553. * It is assumed that the texture has already been created & is currently bound
  67554. */
  67555. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67556. switch (this.loadType) {
  67557. case KhronosTextureContainer.COMPRESSED_2D:
  67558. this._upload2DCompressedLevels(gl, loadMipmaps);
  67559. break;
  67560. case KhronosTextureContainer.TEX_2D:
  67561. case KhronosTextureContainer.COMPRESSED_3D:
  67562. case KhronosTextureContainer.TEX_3D:
  67563. }
  67564. };
  67565. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67566. // initialize width & height for level 1
  67567. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67568. var width = this.pixelWidth;
  67569. var height = this.pixelHeight;
  67570. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67571. for (var level = 0; level < mipmapCount; level++) {
  67572. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67573. for (var face = 0; face < this.numberOfFaces; face++) {
  67574. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67575. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67576. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67577. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67578. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67579. }
  67580. width = Math.max(1.0, width * 0.5);
  67581. height = Math.max(1.0, height * 0.5);
  67582. }
  67583. };
  67584. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67585. // load types
  67586. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67587. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67588. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67589. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67590. return KhronosTextureContainer;
  67591. }());
  67592. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67593. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67594. })(BABYLON || (BABYLON = {}));
  67595. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67596. var BABYLON;
  67597. (function (BABYLON) {
  67598. var Debug;
  67599. (function (Debug) {
  67600. /**
  67601. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67602. */
  67603. var SkeletonViewer = /** @class */ (function () {
  67604. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67605. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67606. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67607. this.skeleton = skeleton;
  67608. this.mesh = mesh;
  67609. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67610. this.renderingGroupId = renderingGroupId;
  67611. this.color = BABYLON.Color3.White();
  67612. this._debugLines = new Array();
  67613. this._isEnabled = false;
  67614. this._scene = scene;
  67615. this.update();
  67616. this._renderFunction = this.update.bind(this);
  67617. }
  67618. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67619. get: function () {
  67620. return this._isEnabled;
  67621. },
  67622. set: function (value) {
  67623. if (this._isEnabled === value) {
  67624. return;
  67625. }
  67626. this._isEnabled = value;
  67627. if (value) {
  67628. this._scene.registerBeforeRender(this._renderFunction);
  67629. }
  67630. else {
  67631. this._scene.unregisterBeforeRender(this._renderFunction);
  67632. }
  67633. },
  67634. enumerable: true,
  67635. configurable: true
  67636. });
  67637. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67638. if (x === void 0) { x = 0; }
  67639. if (y === void 0) { y = 0; }
  67640. if (z === void 0) { z = 0; }
  67641. var tmat = BABYLON.Tmp.Matrix[0];
  67642. var parentBone = bone.getParent();
  67643. tmat.copyFrom(bone.getLocalMatrix());
  67644. if (x !== 0 || y !== 0 || z !== 0) {
  67645. var tmat2 = BABYLON.Tmp.Matrix[1];
  67646. BABYLON.Matrix.IdentityToRef(tmat2);
  67647. tmat2.m[12] = x;
  67648. tmat2.m[13] = y;
  67649. tmat2.m[14] = z;
  67650. tmat2.multiplyToRef(tmat, tmat);
  67651. }
  67652. if (parentBone) {
  67653. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67654. }
  67655. tmat.multiplyToRef(meshMat, tmat);
  67656. position.x = tmat.m[12];
  67657. position.y = tmat.m[13];
  67658. position.z = tmat.m[14];
  67659. };
  67660. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67661. var len = bones.length;
  67662. var meshPos = this.mesh.position;
  67663. for (var i = 0; i < len; i++) {
  67664. var bone = bones[i];
  67665. var points = this._debugLines[i];
  67666. if (!points) {
  67667. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67668. this._debugLines[i] = points;
  67669. }
  67670. this._getBonePosition(points[0], bone, meshMat);
  67671. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67672. points[0].subtractInPlace(meshPos);
  67673. points[1].subtractInPlace(meshPos);
  67674. }
  67675. };
  67676. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67677. var len = bones.length;
  67678. var boneNum = 0;
  67679. var meshPos = this.mesh.position;
  67680. for (var i = len - 1; i >= 0; i--) {
  67681. var childBone = bones[i];
  67682. var parentBone = childBone.getParent();
  67683. if (!parentBone) {
  67684. continue;
  67685. }
  67686. var points = this._debugLines[boneNum];
  67687. if (!points) {
  67688. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67689. this._debugLines[boneNum] = points;
  67690. }
  67691. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67692. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67693. points[0].subtractInPlace(meshPos);
  67694. points[1].subtractInPlace(meshPos);
  67695. boneNum++;
  67696. }
  67697. };
  67698. SkeletonViewer.prototype.update = function () {
  67699. if (this.autoUpdateBonesMatrices) {
  67700. this.skeleton.computeAbsoluteTransforms();
  67701. }
  67702. if (this.skeleton.bones[0].length === undefined) {
  67703. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67704. }
  67705. else {
  67706. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67707. }
  67708. if (!this._debugMesh) {
  67709. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67710. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67711. }
  67712. else {
  67713. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67714. }
  67715. this._debugMesh.position.copyFrom(this.mesh.position);
  67716. this._debugMesh.color = this.color;
  67717. };
  67718. SkeletonViewer.prototype.dispose = function () {
  67719. if (this._debugMesh) {
  67720. this.isEnabled = false;
  67721. this._debugMesh.dispose();
  67722. this._debugMesh = null;
  67723. }
  67724. };
  67725. return SkeletonViewer;
  67726. }());
  67727. Debug.SkeletonViewer = SkeletonViewer;
  67728. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67729. })(BABYLON || (BABYLON = {}));
  67730. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67731. var BABYLON;
  67732. (function (BABYLON) {
  67733. var Debug;
  67734. (function (Debug) {
  67735. var AxesViewer = /** @class */ (function () {
  67736. function AxesViewer(scene, scaleLines) {
  67737. if (scaleLines === void 0) { scaleLines = 1; }
  67738. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67739. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67740. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67741. this.scaleLines = 1;
  67742. this.scaleLines = scaleLines;
  67743. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67744. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67745. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67746. this._xmesh.renderingGroupId = 2;
  67747. this._ymesh.renderingGroupId = 2;
  67748. this._zmesh.renderingGroupId = 2;
  67749. this._xmesh.material.checkReadyOnlyOnce = true;
  67750. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67751. this._ymesh.material.checkReadyOnlyOnce = true;
  67752. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67753. this._zmesh.material.checkReadyOnlyOnce = true;
  67754. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67755. this.scene = scene;
  67756. }
  67757. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67758. var scaleLines = this.scaleLines;
  67759. if (this._xmesh) {
  67760. this._xmesh.position.copyFrom(position);
  67761. }
  67762. if (this._ymesh) {
  67763. this._ymesh.position.copyFrom(position);
  67764. }
  67765. if (this._zmesh) {
  67766. this._zmesh.position.copyFrom(position);
  67767. }
  67768. var point2 = this._xline[1];
  67769. point2.x = xaxis.x * scaleLines;
  67770. point2.y = xaxis.y * scaleLines;
  67771. point2.z = xaxis.z * scaleLines;
  67772. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67773. point2 = this._yline[1];
  67774. point2.x = yaxis.x * scaleLines;
  67775. point2.y = yaxis.y * scaleLines;
  67776. point2.z = yaxis.z * scaleLines;
  67777. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67778. point2 = this._zline[1];
  67779. point2.x = zaxis.x * scaleLines;
  67780. point2.y = zaxis.y * scaleLines;
  67781. point2.z = zaxis.z * scaleLines;
  67782. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67783. };
  67784. AxesViewer.prototype.dispose = function () {
  67785. if (this._xmesh) {
  67786. this._xmesh.dispose();
  67787. }
  67788. if (this._ymesh) {
  67789. this._ymesh.dispose();
  67790. }
  67791. if (this._zmesh) {
  67792. this._zmesh.dispose();
  67793. }
  67794. this._xmesh = null;
  67795. this._ymesh = null;
  67796. this._zmesh = null;
  67797. this.scene = null;
  67798. };
  67799. return AxesViewer;
  67800. }());
  67801. Debug.AxesViewer = AxesViewer;
  67802. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67803. })(BABYLON || (BABYLON = {}));
  67804. //# sourceMappingURL=babylon.axesViewer.js.map
  67805. var BABYLON;
  67806. (function (BABYLON) {
  67807. var Debug;
  67808. (function (Debug) {
  67809. var BoneAxesViewer = /** @class */ (function (_super) {
  67810. __extends(BoneAxesViewer, _super);
  67811. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67812. if (scaleLines === void 0) { scaleLines = 1; }
  67813. var _this = _super.call(this, scene, scaleLines) || this;
  67814. _this.pos = BABYLON.Vector3.Zero();
  67815. _this.xaxis = BABYLON.Vector3.Zero();
  67816. _this.yaxis = BABYLON.Vector3.Zero();
  67817. _this.zaxis = BABYLON.Vector3.Zero();
  67818. _this.mesh = mesh;
  67819. _this.bone = bone;
  67820. return _this;
  67821. }
  67822. BoneAxesViewer.prototype.update = function () {
  67823. if (!this.mesh || !this.bone) {
  67824. return;
  67825. }
  67826. var bone = this.bone;
  67827. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67828. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67829. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67830. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67831. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67832. };
  67833. BoneAxesViewer.prototype.dispose = function () {
  67834. if (this.mesh) {
  67835. this.mesh = null;
  67836. this.bone = null;
  67837. _super.prototype.dispose.call(this);
  67838. }
  67839. };
  67840. return BoneAxesViewer;
  67841. }(Debug.AxesViewer));
  67842. Debug.BoneAxesViewer = BoneAxesViewer;
  67843. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67844. })(BABYLON || (BABYLON = {}));
  67845. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67846. var BABYLON;
  67847. (function (BABYLON) {
  67848. var RayHelper = /** @class */ (function () {
  67849. function RayHelper(ray) {
  67850. this.ray = ray;
  67851. }
  67852. RayHelper.CreateAndShow = function (ray, scene, color) {
  67853. var helper = new RayHelper(ray);
  67854. helper.show(scene, color);
  67855. return helper;
  67856. };
  67857. RayHelper.prototype.show = function (scene, color) {
  67858. if (!this._renderFunction && this.ray) {
  67859. var ray = this.ray;
  67860. this._renderFunction = this._render.bind(this);
  67861. this._scene = scene;
  67862. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67863. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67864. if (this._renderFunction) {
  67865. this._scene.registerBeforeRender(this._renderFunction);
  67866. }
  67867. }
  67868. if (color && this._renderLine) {
  67869. this._renderLine.color.copyFrom(color);
  67870. }
  67871. };
  67872. RayHelper.prototype.hide = function () {
  67873. if (this._renderFunction && this._scene) {
  67874. this._scene.unregisterBeforeRender(this._renderFunction);
  67875. this._scene = null;
  67876. this._renderFunction = null;
  67877. if (this._renderLine) {
  67878. this._renderLine.dispose();
  67879. this._renderLine = null;
  67880. }
  67881. this._renderPoints = [];
  67882. }
  67883. };
  67884. RayHelper.prototype._render = function () {
  67885. var ray = this.ray;
  67886. if (!ray) {
  67887. return;
  67888. }
  67889. var point = this._renderPoints[1];
  67890. var len = Math.min(ray.length, 1000000);
  67891. point.copyFrom(ray.direction);
  67892. point.scaleInPlace(len);
  67893. point.addInPlace(ray.origin);
  67894. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67895. };
  67896. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67897. this._attachedToMesh = mesh;
  67898. var ray = this.ray;
  67899. if (!ray) {
  67900. return;
  67901. }
  67902. if (!ray.direction) {
  67903. ray.direction = BABYLON.Vector3.Zero();
  67904. }
  67905. if (!ray.origin) {
  67906. ray.origin = BABYLON.Vector3.Zero();
  67907. }
  67908. if (length) {
  67909. ray.length = length;
  67910. }
  67911. if (!meshSpaceOrigin) {
  67912. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67913. }
  67914. if (!meshSpaceDirection) {
  67915. // -1 so that this will work with Mesh.lookAt
  67916. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67917. }
  67918. if (!this._meshSpaceDirection) {
  67919. this._meshSpaceDirection = meshSpaceDirection.clone();
  67920. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67921. }
  67922. else {
  67923. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67924. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67925. }
  67926. if (!this._updateToMeshFunction) {
  67927. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67928. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67929. }
  67930. this._updateToMesh();
  67931. };
  67932. RayHelper.prototype.detachFromMesh = function () {
  67933. if (this._attachedToMesh) {
  67934. if (this._updateToMeshFunction) {
  67935. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67936. }
  67937. this._attachedToMesh = null;
  67938. this._updateToMeshFunction = null;
  67939. }
  67940. };
  67941. RayHelper.prototype._updateToMesh = function () {
  67942. var ray = this.ray;
  67943. if (!this._attachedToMesh || !ray) {
  67944. return;
  67945. }
  67946. if (this._attachedToMesh._isDisposed) {
  67947. this.detachFromMesh();
  67948. return;
  67949. }
  67950. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67951. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67952. };
  67953. RayHelper.prototype.dispose = function () {
  67954. this.hide();
  67955. this.detachFromMesh();
  67956. this.ray = null;
  67957. };
  67958. return RayHelper;
  67959. }());
  67960. BABYLON.RayHelper = RayHelper;
  67961. })(BABYLON || (BABYLON = {}));
  67962. //# sourceMappingURL=babylon.rayHelper.js.map
  67963. var BABYLON;
  67964. (function (BABYLON) {
  67965. var DebugLayer = /** @class */ (function () {
  67966. function DebugLayer(scene) {
  67967. this._scene = scene;
  67968. }
  67969. /** Creates the inspector window. */
  67970. DebugLayer.prototype._createInspector = function (config) {
  67971. if (config === void 0) { config = {}; }
  67972. var popup = config.popup || false;
  67973. var initialTab = config.initialTab || 0;
  67974. var parentElement = config.parentElement || null;
  67975. if (!this._inspector) {
  67976. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67977. } // else nothing to do,; instance is already existing
  67978. };
  67979. DebugLayer.prototype.isVisible = function () {
  67980. if (!this._inspector) {
  67981. return false;
  67982. }
  67983. return true;
  67984. };
  67985. DebugLayer.prototype.hide = function () {
  67986. if (this._inspector) {
  67987. try {
  67988. this._inspector.dispose();
  67989. }
  67990. catch (e) {
  67991. // If the inspector has been removed directly from the inspector tool
  67992. }
  67993. this._inspector = null;
  67994. }
  67995. };
  67996. DebugLayer.prototype.show = function (config) {
  67997. if (config === void 0) { config = {}; }
  67998. if (typeof INSPECTOR == 'undefined') {
  67999. // Load inspector and add it to the DOM
  68000. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  68001. }
  68002. else {
  68003. // Otherwise creates the inspector
  68004. this._createInspector(config);
  68005. }
  68006. };
  68007. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  68008. return DebugLayer;
  68009. }());
  68010. BABYLON.DebugLayer = DebugLayer;
  68011. })(BABYLON || (BABYLON = {}));
  68012. //# sourceMappingURL=babylon.debugLayer.js.map
  68013. var BABYLON;
  68014. (function (BABYLON) {
  68015. var Debug;
  68016. (function (Debug) {
  68017. var PhysicsViewer = /** @class */ (function () {
  68018. function PhysicsViewer(scene) {
  68019. this._impostors = [];
  68020. this._meshes = [];
  68021. this._numMeshes = 0;
  68022. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68023. var physicEngine = this._scene.getPhysicsEngine();
  68024. if (physicEngine) {
  68025. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  68026. }
  68027. }
  68028. PhysicsViewer.prototype._updateDebugMeshes = function () {
  68029. var plugin = this._physicsEnginePlugin;
  68030. for (var i = 0; i < this._numMeshes; i++) {
  68031. var impostor = this._impostors[i];
  68032. if (!impostor) {
  68033. continue;
  68034. }
  68035. if (impostor.isDisposed) {
  68036. this.hideImpostor(this._impostors[i--]);
  68037. }
  68038. else {
  68039. var mesh = this._meshes[i];
  68040. if (mesh && plugin) {
  68041. plugin.syncMeshWithImpostor(mesh, impostor);
  68042. }
  68043. }
  68044. }
  68045. };
  68046. PhysicsViewer.prototype.showImpostor = function (impostor) {
  68047. if (!this._scene) {
  68048. return;
  68049. }
  68050. for (var i = 0; i < this._numMeshes; i++) {
  68051. if (this._impostors[i] == impostor) {
  68052. return;
  68053. }
  68054. }
  68055. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68056. if (debugMesh) {
  68057. this._impostors[this._numMeshes] = impostor;
  68058. this._meshes[this._numMeshes] = debugMesh;
  68059. if (this._numMeshes === 0) {
  68060. this._renderFunction = this._updateDebugMeshes.bind(this);
  68061. this._scene.registerBeforeRender(this._renderFunction);
  68062. }
  68063. this._numMeshes++;
  68064. }
  68065. };
  68066. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68067. if (!impostor || !this._scene) {
  68068. return;
  68069. }
  68070. var removed = false;
  68071. for (var i = 0; i < this._numMeshes; i++) {
  68072. if (this._impostors[i] == impostor) {
  68073. var mesh = this._meshes[i];
  68074. if (!mesh) {
  68075. continue;
  68076. }
  68077. this._scene.removeMesh(mesh);
  68078. mesh.dispose();
  68079. this._numMeshes--;
  68080. if (this._numMeshes > 0) {
  68081. this._meshes[i] = this._meshes[this._numMeshes];
  68082. this._impostors[i] = this._impostors[this._numMeshes];
  68083. this._meshes[this._numMeshes] = null;
  68084. this._impostors[this._numMeshes] = null;
  68085. }
  68086. else {
  68087. this._meshes[0] = null;
  68088. this._impostors[0] = null;
  68089. }
  68090. removed = true;
  68091. break;
  68092. }
  68093. }
  68094. if (removed && this._numMeshes === 0) {
  68095. this._scene.unregisterBeforeRender(this._renderFunction);
  68096. }
  68097. };
  68098. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68099. if (!this._debugMaterial) {
  68100. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68101. this._debugMaterial.wireframe = true;
  68102. }
  68103. return this._debugMaterial;
  68104. };
  68105. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68106. if (!this._debugBoxMesh) {
  68107. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68108. this._debugBoxMesh.renderingGroupId = 1;
  68109. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68110. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68111. scene.removeMesh(this._debugBoxMesh);
  68112. }
  68113. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68114. };
  68115. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68116. if (!this._debugSphereMesh) {
  68117. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68118. this._debugSphereMesh.renderingGroupId = 1;
  68119. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68120. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68121. scene.removeMesh(this._debugSphereMesh);
  68122. }
  68123. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68124. };
  68125. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68126. var mesh = null;
  68127. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68128. mesh = this._getDebugBoxMesh(scene);
  68129. impostor.getBoxSizeToRef(mesh.scaling);
  68130. }
  68131. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68132. mesh = this._getDebugSphereMesh(scene);
  68133. var radius = impostor.getRadius();
  68134. mesh.scaling.x = radius * 2;
  68135. mesh.scaling.y = radius * 2;
  68136. mesh.scaling.z = radius * 2;
  68137. }
  68138. return mesh;
  68139. };
  68140. PhysicsViewer.prototype.dispose = function () {
  68141. for (var i = 0; i < this._numMeshes; i++) {
  68142. this.hideImpostor(this._impostors[i]);
  68143. }
  68144. if (this._debugBoxMesh) {
  68145. this._debugBoxMesh.dispose();
  68146. }
  68147. if (this._debugSphereMesh) {
  68148. this._debugSphereMesh.dispose();
  68149. }
  68150. if (this._debugMaterial) {
  68151. this._debugMaterial.dispose();
  68152. }
  68153. this._impostors.length = 0;
  68154. this._scene = null;
  68155. this._physicsEnginePlugin = null;
  68156. };
  68157. return PhysicsViewer;
  68158. }());
  68159. Debug.PhysicsViewer = PhysicsViewer;
  68160. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68161. })(BABYLON || (BABYLON = {}));
  68162. //# sourceMappingURL=babylon.physicsViewer.js.map
  68163. var BABYLON;
  68164. (function (BABYLON) {
  68165. var BoundingBoxRenderer = /** @class */ (function () {
  68166. function BoundingBoxRenderer(scene) {
  68167. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68168. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68169. this.showBackLines = true;
  68170. this.renderList = new BABYLON.SmartArray(32);
  68171. this._vertexBuffers = {};
  68172. this._scene = scene;
  68173. }
  68174. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68175. if (this._colorShader) {
  68176. return;
  68177. }
  68178. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68179. attributes: [BABYLON.VertexBuffer.PositionKind],
  68180. uniforms: ["world", "viewProjection", "color"]
  68181. });
  68182. var engine = this._scene.getEngine();
  68183. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68184. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68185. this._createIndexBuffer();
  68186. };
  68187. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68188. var engine = this._scene.getEngine();
  68189. 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]);
  68190. };
  68191. BoundingBoxRenderer.prototype._rebuild = function () {
  68192. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68193. if (vb) {
  68194. vb._rebuild();
  68195. }
  68196. this._createIndexBuffer();
  68197. };
  68198. BoundingBoxRenderer.prototype.reset = function () {
  68199. this.renderList.reset();
  68200. };
  68201. BoundingBoxRenderer.prototype.render = function () {
  68202. if (this.renderList.length === 0) {
  68203. return;
  68204. }
  68205. this._prepareRessources();
  68206. if (!this._colorShader.isReady()) {
  68207. return;
  68208. }
  68209. var engine = this._scene.getEngine();
  68210. engine.setDepthWrite(false);
  68211. this._colorShader._preBind();
  68212. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68213. var boundingBox = this.renderList.data[boundingBoxIndex];
  68214. var min = boundingBox.minimum;
  68215. var max = boundingBox.maximum;
  68216. var diff = max.subtract(min);
  68217. var median = min.add(diff.scale(0.5));
  68218. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68219. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68220. .multiply(boundingBox.getWorldMatrix());
  68221. // VBOs
  68222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68223. if (this.showBackLines) {
  68224. // Back
  68225. engine.setDepthFunctionToGreaterOrEqual();
  68226. this._scene.resetCachedMaterial();
  68227. this._colorShader.setColor4("color", this.backColor.toColor4());
  68228. this._colorShader.bind(worldMatrix);
  68229. // Draw order
  68230. engine.draw(false, 0, 24);
  68231. }
  68232. // Front
  68233. engine.setDepthFunctionToLess();
  68234. this._scene.resetCachedMaterial();
  68235. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68236. this._colorShader.bind(worldMatrix);
  68237. // Draw order
  68238. engine.draw(false, 0, 24);
  68239. }
  68240. this._colorShader.unbind();
  68241. engine.setDepthFunctionToLessOrEqual();
  68242. engine.setDepthWrite(true);
  68243. };
  68244. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68245. this._prepareRessources();
  68246. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68247. return;
  68248. }
  68249. var engine = this._scene.getEngine();
  68250. engine.setDepthWrite(false);
  68251. engine.setColorWrite(false);
  68252. this._colorShader._preBind();
  68253. var boundingBox = mesh._boundingInfo.boundingBox;
  68254. var min = boundingBox.minimum;
  68255. var max = boundingBox.maximum;
  68256. var diff = max.subtract(min);
  68257. var median = min.add(diff.scale(0.5));
  68258. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68259. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68260. .multiply(boundingBox.getWorldMatrix());
  68261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68262. engine.setDepthFunctionToLess();
  68263. this._scene.resetCachedMaterial();
  68264. this._colorShader.bind(worldMatrix);
  68265. engine.draw(false, 0, 24);
  68266. this._colorShader.unbind();
  68267. engine.setDepthFunctionToLessOrEqual();
  68268. engine.setDepthWrite(true);
  68269. engine.setColorWrite(true);
  68270. };
  68271. BoundingBoxRenderer.prototype.dispose = function () {
  68272. if (!this._colorShader) {
  68273. return;
  68274. }
  68275. this.renderList.dispose();
  68276. this._colorShader.dispose();
  68277. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68278. if (buffer) {
  68279. buffer.dispose();
  68280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68281. }
  68282. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68283. };
  68284. return BoundingBoxRenderer;
  68285. }());
  68286. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68287. })(BABYLON || (BABYLON = {}));
  68288. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68289. var BABYLON;
  68290. (function (BABYLON) {
  68291. var MorphTarget = /** @class */ (function () {
  68292. function MorphTarget(name, influence) {
  68293. if (influence === void 0) { influence = 0; }
  68294. this.name = name;
  68295. this.animations = new Array();
  68296. this._positions = null;
  68297. this._normals = null;
  68298. this._tangents = null;
  68299. this.onInfluenceChanged = new BABYLON.Observable();
  68300. this.influence = influence;
  68301. }
  68302. Object.defineProperty(MorphTarget.prototype, "influence", {
  68303. get: function () {
  68304. return this._influence;
  68305. },
  68306. set: function (influence) {
  68307. if (this._influence === influence) {
  68308. return;
  68309. }
  68310. var previous = this._influence;
  68311. this._influence = influence;
  68312. if (this.onInfluenceChanged.hasObservers) {
  68313. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68314. }
  68315. },
  68316. enumerable: true,
  68317. configurable: true
  68318. });
  68319. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68320. get: function () {
  68321. return !!this._positions;
  68322. },
  68323. enumerable: true,
  68324. configurable: true
  68325. });
  68326. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68327. get: function () {
  68328. return !!this._normals;
  68329. },
  68330. enumerable: true,
  68331. configurable: true
  68332. });
  68333. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68334. get: function () {
  68335. return !!this._tangents;
  68336. },
  68337. enumerable: true,
  68338. configurable: true
  68339. });
  68340. MorphTarget.prototype.setPositions = function (data) {
  68341. this._positions = data;
  68342. };
  68343. MorphTarget.prototype.getPositions = function () {
  68344. return this._positions;
  68345. };
  68346. MorphTarget.prototype.setNormals = function (data) {
  68347. this._normals = data;
  68348. };
  68349. MorphTarget.prototype.getNormals = function () {
  68350. return this._normals;
  68351. };
  68352. MorphTarget.prototype.setTangents = function (data) {
  68353. this._tangents = data;
  68354. };
  68355. MorphTarget.prototype.getTangents = function () {
  68356. return this._tangents;
  68357. };
  68358. /**
  68359. * Serializes the current target into a Serialization object.
  68360. * Returns the serialized object.
  68361. */
  68362. MorphTarget.prototype.serialize = function () {
  68363. var serializationObject = {};
  68364. serializationObject.name = this.name;
  68365. serializationObject.influence = this.influence;
  68366. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68367. if (this.hasNormals) {
  68368. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68369. }
  68370. if (this.hasTangents) {
  68371. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68372. }
  68373. // Animations
  68374. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68375. return serializationObject;
  68376. };
  68377. // Statics
  68378. MorphTarget.Parse = function (serializationObject) {
  68379. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68380. result.setPositions(serializationObject.positions);
  68381. if (serializationObject.normals) {
  68382. result.setNormals(serializationObject.normals);
  68383. }
  68384. if (serializationObject.tangents) {
  68385. result.setTangents(serializationObject.tangents);
  68386. }
  68387. // Animations
  68388. if (serializationObject.animations) {
  68389. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68390. var parsedAnimation = serializationObject.animations[animationIndex];
  68391. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68392. }
  68393. }
  68394. return result;
  68395. };
  68396. MorphTarget.FromMesh = function (mesh, name, influence) {
  68397. if (!name) {
  68398. name = mesh.name;
  68399. }
  68400. var result = new MorphTarget(name, influence);
  68401. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68402. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68403. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68404. }
  68405. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68406. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68407. }
  68408. return result;
  68409. };
  68410. return MorphTarget;
  68411. }());
  68412. BABYLON.MorphTarget = MorphTarget;
  68413. })(BABYLON || (BABYLON = {}));
  68414. //# sourceMappingURL=babylon.morphTarget.js.map
  68415. var BABYLON;
  68416. (function (BABYLON) {
  68417. var MorphTargetManager = /** @class */ (function () {
  68418. function MorphTargetManager(scene) {
  68419. if (scene === void 0) { scene = null; }
  68420. this._targets = new Array();
  68421. this._targetObservable = new Array();
  68422. this._activeTargets = new BABYLON.SmartArray(16);
  68423. this._supportsNormals = false;
  68424. this._supportsTangents = false;
  68425. this._vertexCount = 0;
  68426. this._uniqueId = 0;
  68427. this._tempInfluences = new Array();
  68428. if (!scene) {
  68429. scene = BABYLON.Engine.LastCreatedScene;
  68430. }
  68431. this._scene = scene;
  68432. if (this._scene) {
  68433. this._scene.morphTargetManagers.push(this);
  68434. this._uniqueId = this._scene.getUniqueId();
  68435. }
  68436. }
  68437. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68438. get: function () {
  68439. return this._uniqueId;
  68440. },
  68441. enumerable: true,
  68442. configurable: true
  68443. });
  68444. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68445. get: function () {
  68446. return this._vertexCount;
  68447. },
  68448. enumerable: true,
  68449. configurable: true
  68450. });
  68451. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68452. get: function () {
  68453. return this._supportsNormals;
  68454. },
  68455. enumerable: true,
  68456. configurable: true
  68457. });
  68458. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68459. get: function () {
  68460. return this._supportsTangents;
  68461. },
  68462. enumerable: true,
  68463. configurable: true
  68464. });
  68465. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68466. get: function () {
  68467. return this._targets.length;
  68468. },
  68469. enumerable: true,
  68470. configurable: true
  68471. });
  68472. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68473. get: function () {
  68474. return this._activeTargets.length;
  68475. },
  68476. enumerable: true,
  68477. configurable: true
  68478. });
  68479. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68480. get: function () {
  68481. return this._influences;
  68482. },
  68483. enumerable: true,
  68484. configurable: true
  68485. });
  68486. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68487. return this._activeTargets.data[index];
  68488. };
  68489. MorphTargetManager.prototype.getTarget = function (index) {
  68490. return this._targets[index];
  68491. };
  68492. MorphTargetManager.prototype.addTarget = function (target) {
  68493. var _this = this;
  68494. this._targets.push(target);
  68495. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68496. _this._syncActiveTargets(needUpdate);
  68497. }));
  68498. this._syncActiveTargets(true);
  68499. };
  68500. MorphTargetManager.prototype.removeTarget = function (target) {
  68501. var index = this._targets.indexOf(target);
  68502. if (index >= 0) {
  68503. this._targets.splice(index, 1);
  68504. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68505. this._syncActiveTargets(true);
  68506. }
  68507. };
  68508. /**
  68509. * Serializes the current manager into a Serialization object.
  68510. * Returns the serialized object.
  68511. */
  68512. MorphTargetManager.prototype.serialize = function () {
  68513. var serializationObject = {};
  68514. serializationObject.id = this.uniqueId;
  68515. serializationObject.targets = [];
  68516. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68517. var target = _a[_i];
  68518. serializationObject.targets.push(target.serialize());
  68519. }
  68520. return serializationObject;
  68521. };
  68522. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68523. var influenceCount = 0;
  68524. this._activeTargets.reset();
  68525. this._supportsNormals = true;
  68526. this._supportsTangents = true;
  68527. this._vertexCount = 0;
  68528. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68529. var target = _a[_i];
  68530. if (target.influence > 0) {
  68531. this._activeTargets.push(target);
  68532. this._tempInfluences[influenceCount++] = target.influence;
  68533. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68534. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68535. var positions = target.getPositions();
  68536. if (!positions) {
  68537. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68538. return;
  68539. }
  68540. var vertexCount = positions.length / 3;
  68541. if (this._vertexCount === 0) {
  68542. this._vertexCount = vertexCount;
  68543. }
  68544. else if (this._vertexCount !== vertexCount) {
  68545. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68546. return;
  68547. }
  68548. }
  68549. }
  68550. if (!this._influences || this._influences.length !== influenceCount) {
  68551. this._influences = new Float32Array(influenceCount);
  68552. }
  68553. for (var index = 0; index < influenceCount; index++) {
  68554. this._influences[index] = this._tempInfluences[index];
  68555. }
  68556. if (needUpdate && this._scene) {
  68557. // Flag meshes as dirty to resync with the active targets
  68558. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68559. var mesh = _c[_b];
  68560. if (mesh.morphTargetManager === this) {
  68561. mesh._syncGeometryWithMorphTargetManager();
  68562. }
  68563. }
  68564. }
  68565. };
  68566. // Statics
  68567. MorphTargetManager.Parse = function (serializationObject, scene) {
  68568. var result = new MorphTargetManager(scene);
  68569. result._uniqueId = serializationObject.id;
  68570. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68571. var targetData = _a[_i];
  68572. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68573. }
  68574. return result;
  68575. };
  68576. return MorphTargetManager;
  68577. }());
  68578. BABYLON.MorphTargetManager = MorphTargetManager;
  68579. })(BABYLON || (BABYLON = {}));
  68580. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68581. var BABYLON;
  68582. (function (BABYLON) {
  68583. var Octree = /** @class */ (function () {
  68584. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68585. if (maxDepth === void 0) { maxDepth = 2; }
  68586. this.maxDepth = maxDepth;
  68587. this.dynamicContent = new Array();
  68588. this._maxBlockCapacity = maxBlockCapacity || 64;
  68589. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  68590. this._creationFunc = creationFunc;
  68591. }
  68592. // Methods
  68593. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68594. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68595. };
  68596. Octree.prototype.addMesh = function (entry) {
  68597. for (var index = 0; index < this.blocks.length; index++) {
  68598. var block = this.blocks[index];
  68599. block.addEntry(entry);
  68600. }
  68601. };
  68602. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68603. this._selectionContent.reset();
  68604. for (var index = 0; index < this.blocks.length; index++) {
  68605. var block = this.blocks[index];
  68606. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68607. }
  68608. if (allowDuplicate) {
  68609. this._selectionContent.concat(this.dynamicContent);
  68610. }
  68611. else {
  68612. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68613. }
  68614. return this._selectionContent;
  68615. };
  68616. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68617. this._selectionContent.reset();
  68618. for (var index = 0; index < this.blocks.length; index++) {
  68619. var block = this.blocks[index];
  68620. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68621. }
  68622. if (allowDuplicate) {
  68623. this._selectionContent.concat(this.dynamicContent);
  68624. }
  68625. else {
  68626. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68627. }
  68628. return this._selectionContent;
  68629. };
  68630. Octree.prototype.intersectsRay = function (ray) {
  68631. this._selectionContent.reset();
  68632. for (var index = 0; index < this.blocks.length; index++) {
  68633. var block = this.blocks[index];
  68634. block.intersectsRay(ray, this._selectionContent);
  68635. }
  68636. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68637. return this._selectionContent;
  68638. };
  68639. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68640. target.blocks = new Array();
  68641. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68642. // Segmenting space
  68643. for (var x = 0; x < 2; x++) {
  68644. for (var y = 0; y < 2; y++) {
  68645. for (var z = 0; z < 2; z++) {
  68646. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68647. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68648. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68649. block.addEntries(entries);
  68650. target.blocks.push(block);
  68651. }
  68652. }
  68653. }
  68654. };
  68655. Octree.CreationFuncForMeshes = function (entry, block) {
  68656. var boundingInfo = entry.getBoundingInfo();
  68657. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68658. block.entries.push(entry);
  68659. }
  68660. };
  68661. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68662. var boundingInfo = entry.getBoundingInfo();
  68663. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68664. block.entries.push(entry);
  68665. }
  68666. };
  68667. return Octree;
  68668. }());
  68669. BABYLON.Octree = Octree;
  68670. })(BABYLON || (BABYLON = {}));
  68671. //# sourceMappingURL=babylon.octree.js.map
  68672. var BABYLON;
  68673. (function (BABYLON) {
  68674. var OctreeBlock = /** @class */ (function () {
  68675. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68676. this.entries = new Array();
  68677. this._boundingVectors = new Array();
  68678. this._capacity = capacity;
  68679. this._depth = depth;
  68680. this._maxDepth = maxDepth;
  68681. this._creationFunc = creationFunc;
  68682. this._minPoint = minPoint;
  68683. this._maxPoint = maxPoint;
  68684. this._boundingVectors.push(minPoint.clone());
  68685. this._boundingVectors.push(maxPoint.clone());
  68686. this._boundingVectors.push(minPoint.clone());
  68687. this._boundingVectors[2].x = maxPoint.x;
  68688. this._boundingVectors.push(minPoint.clone());
  68689. this._boundingVectors[3].y = maxPoint.y;
  68690. this._boundingVectors.push(minPoint.clone());
  68691. this._boundingVectors[4].z = maxPoint.z;
  68692. this._boundingVectors.push(maxPoint.clone());
  68693. this._boundingVectors[5].z = minPoint.z;
  68694. this._boundingVectors.push(maxPoint.clone());
  68695. this._boundingVectors[6].x = minPoint.x;
  68696. this._boundingVectors.push(maxPoint.clone());
  68697. this._boundingVectors[7].y = minPoint.y;
  68698. }
  68699. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68700. // Property
  68701. get: function () {
  68702. return this._capacity;
  68703. },
  68704. enumerable: true,
  68705. configurable: true
  68706. });
  68707. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68708. get: function () {
  68709. return this._minPoint;
  68710. },
  68711. enumerable: true,
  68712. configurable: true
  68713. });
  68714. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68715. get: function () {
  68716. return this._maxPoint;
  68717. },
  68718. enumerable: true,
  68719. configurable: true
  68720. });
  68721. // Methods
  68722. OctreeBlock.prototype.addEntry = function (entry) {
  68723. if (this.blocks) {
  68724. for (var index = 0; index < this.blocks.length; index++) {
  68725. var block = this.blocks[index];
  68726. block.addEntry(entry);
  68727. }
  68728. return;
  68729. }
  68730. this._creationFunc(entry, this);
  68731. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68732. this.createInnerBlocks();
  68733. }
  68734. };
  68735. OctreeBlock.prototype.addEntries = function (entries) {
  68736. for (var index = 0; index < entries.length; index++) {
  68737. var mesh = entries[index];
  68738. this.addEntry(mesh);
  68739. }
  68740. };
  68741. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68742. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68743. if (this.blocks) {
  68744. for (var index = 0; index < this.blocks.length; index++) {
  68745. var block = this.blocks[index];
  68746. block.select(frustumPlanes, selection, allowDuplicate);
  68747. }
  68748. return;
  68749. }
  68750. if (allowDuplicate) {
  68751. selection.concat(this.entries);
  68752. }
  68753. else {
  68754. selection.concatWithNoDuplicate(this.entries);
  68755. }
  68756. }
  68757. };
  68758. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68759. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68760. if (this.blocks) {
  68761. for (var index = 0; index < this.blocks.length; index++) {
  68762. var block = this.blocks[index];
  68763. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68764. }
  68765. return;
  68766. }
  68767. if (allowDuplicate) {
  68768. selection.concat(this.entries);
  68769. }
  68770. else {
  68771. selection.concatWithNoDuplicate(this.entries);
  68772. }
  68773. }
  68774. };
  68775. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68776. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68777. if (this.blocks) {
  68778. for (var index = 0; index < this.blocks.length; index++) {
  68779. var block = this.blocks[index];
  68780. block.intersectsRay(ray, selection);
  68781. }
  68782. return;
  68783. }
  68784. selection.concatWithNoDuplicate(this.entries);
  68785. }
  68786. };
  68787. OctreeBlock.prototype.createInnerBlocks = function () {
  68788. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68789. };
  68790. return OctreeBlock;
  68791. }());
  68792. BABYLON.OctreeBlock = OctreeBlock;
  68793. })(BABYLON || (BABYLON = {}));
  68794. //# sourceMappingURL=babylon.octreeBlock.js.map
  68795. var BABYLON;
  68796. (function (BABYLON) {
  68797. var SIMDVector3 = /** @class */ (function () {
  68798. function SIMDVector3() {
  68799. }
  68800. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68801. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68802. };
  68803. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68804. var m = transformation.m;
  68805. var m0 = SIMD.Float32x4.load(m, 0);
  68806. var m1 = SIMD.Float32x4.load(m, 4);
  68807. var m2 = SIMD.Float32x4.load(m, 8);
  68808. var m3 = SIMD.Float32x4.load(m, 12);
  68809. 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));
  68810. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68811. result.x = SIMD.Float32x4.extractLane(r, 0);
  68812. result.y = SIMD.Float32x4.extractLane(r, 1);
  68813. result.z = SIMD.Float32x4.extractLane(r, 2);
  68814. };
  68815. return SIMDVector3;
  68816. }());
  68817. var SIMDMatrix = /** @class */ (function () {
  68818. function SIMDMatrix() {
  68819. }
  68820. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68821. var tm = this.m;
  68822. var om = other.m;
  68823. var m0 = SIMD.Float32x4.load(om, 0);
  68824. var m1 = SIMD.Float32x4.load(om, 4);
  68825. var m2 = SIMD.Float32x4.load(om, 8);
  68826. var m3 = SIMD.Float32x4.load(om, 12);
  68827. for (var i = 0; i < 16; i += 4) {
  68828. 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)))));
  68829. }
  68830. return this;
  68831. };
  68832. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68833. var src = this.m;
  68834. var dest = other.m;
  68835. // Load the 4 rows
  68836. var src0 = SIMD.Float32x4.load(src, 0);
  68837. var src1 = SIMD.Float32x4.load(src, 4);
  68838. var src2 = SIMD.Float32x4.load(src, 8);
  68839. var src3 = SIMD.Float32x4.load(src, 12);
  68840. // Transpose the source matrix. Sort of. Not a true transpose operation
  68841. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68842. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68843. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68844. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68845. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68846. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68847. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68848. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68849. // This is a true transposition, but it will lead to an incorrect result
  68850. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68851. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68852. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68853. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68854. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68855. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68856. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68857. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68858. // ----
  68859. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68860. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68861. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68862. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68863. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68864. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68865. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68866. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68867. // ----
  68868. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68869. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68870. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68871. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68872. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68873. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68874. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68875. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68876. // ----
  68877. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68878. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68879. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68880. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68881. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68882. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68883. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68884. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68885. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68886. // ----
  68887. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68888. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68889. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68890. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68891. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68892. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68893. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68894. // ----
  68895. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68896. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68897. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68898. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68899. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68900. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68901. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68902. // ----
  68903. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68904. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68905. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68906. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68907. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68908. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68909. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68910. // Compute determinant
  68911. var det = SIMD.Float32x4.mul(row0, minor0);
  68912. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68913. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68914. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68915. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68916. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68917. // These shuffles aren't necessary if the faulty transposition is done
  68918. // up at the top of this function.
  68919. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68920. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68921. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68922. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68923. // Compute final values by multiplying with 1/det
  68924. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68925. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68926. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68927. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68928. return this;
  68929. };
  68930. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68931. var out = result.m;
  68932. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68933. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68934. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68935. // cc.kmVec3Subtract(f, pCenter, pEye);
  68936. var f = SIMD.Float32x4.sub(center, eye);
  68937. // cc.kmVec3Normalize(f, f);
  68938. var tmp = SIMD.Float32x4.mul(f, f);
  68939. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68940. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68941. // cc.kmVec3Assign(up, pUp);
  68942. // cc.kmVec3Normalize(up, up);
  68943. tmp = SIMD.Float32x4.mul(up, up);
  68944. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68945. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68946. // cc.kmVec3Cross(s, f, up);
  68947. 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)));
  68948. // cc.kmVec3Normalize(s, s);
  68949. tmp = SIMD.Float32x4.mul(s, s);
  68950. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68951. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68952. // cc.kmVec3Cross(u, s, f);
  68953. 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)));
  68954. // cc.kmVec3Normalize(s, s);
  68955. tmp = SIMD.Float32x4.mul(s, s);
  68956. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68957. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68958. var zero = SIMD.Float32x4.splat(0.0);
  68959. s = SIMD.Float32x4.neg(s);
  68960. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68961. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68962. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68963. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68964. 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);
  68965. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68966. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68967. 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)))));
  68968. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68969. 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)))));
  68970. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68971. 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)))));
  68972. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68973. 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)))));
  68974. };
  68975. return SIMDMatrix;
  68976. }());
  68977. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68978. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68979. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68980. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68981. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68982. var SIMDHelper = /** @class */ (function () {
  68983. function SIMDHelper() {
  68984. }
  68985. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68986. get: function () {
  68987. return SIMDHelper._isEnabled;
  68988. },
  68989. enumerable: true,
  68990. configurable: true
  68991. });
  68992. SIMDHelper.DisableSIMD = function () {
  68993. // Replace functions
  68994. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68995. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68996. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68997. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68998. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68999. SIMDHelper._isEnabled = false;
  69000. };
  69001. SIMDHelper.EnableSIMD = function () {
  69002. if (self.SIMD === undefined) {
  69003. return;
  69004. }
  69005. // check if polyfills needed
  69006. if (!self.Math.fround) {
  69007. self.Math.fround = (function (array) { return function (x) {
  69008. return array[0] = x, array[0];
  69009. }; })(new Float32Array(1));
  69010. }
  69011. if (!self.Math.imul) {
  69012. self.Math.imul = function (a, b) {
  69013. var ah = (a >>> 16) & 0xffff;
  69014. var al = a & 0xffff;
  69015. var bh = (b >>> 16) & 0xffff;
  69016. var bl = b & 0xffff;
  69017. // the shift by 0 fixes the sign on the high part
  69018. // the final |0 converts the unsigned value into a signed value
  69019. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  69020. };
  69021. }
  69022. // Replace functions
  69023. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  69024. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  69025. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  69026. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  69027. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  69028. SIMDHelper._isEnabled = true;
  69029. };
  69030. SIMDHelper._isEnabled = false;
  69031. return SIMDHelper;
  69032. }());
  69033. BABYLON.SIMDHelper = SIMDHelper;
  69034. })(BABYLON || (BABYLON = {}));
  69035. //# sourceMappingURL=babylon.math.SIMD.js.map
  69036. var BABYLON;
  69037. (function (BABYLON) {
  69038. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  69039. __extends(VRDistortionCorrectionPostProcess, _super);
  69040. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  69041. var _this = _super.call(this, name, "vrDistortionCorrection", [
  69042. 'LensCenter',
  69043. 'Scale',
  69044. 'ScaleIn',
  69045. 'HmdWarpParam'
  69046. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  69047. _this._isRightEye = isRightEye;
  69048. _this._distortionFactors = vrMetrics.distortionK;
  69049. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69050. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69051. _this.adaptScaleToCurrentViewport = true;
  69052. _this.onSizeChangedObservable.add(function () {
  69053. _this.aspectRatio = _this.width * .5 / _this.height;
  69054. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69055. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69056. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69057. });
  69058. _this.onApplyObservable.add(function (effect) {
  69059. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69060. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69061. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69062. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69063. });
  69064. return _this;
  69065. }
  69066. return VRDistortionCorrectionPostProcess;
  69067. }(BABYLON.PostProcess));
  69068. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69069. })(BABYLON || (BABYLON = {}));
  69070. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69071. var BABYLON;
  69072. (function (BABYLON) {
  69073. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69074. __extends(AnaglyphPostProcess, _super);
  69075. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69076. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69077. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69078. _this.onApplyObservable.add(function (effect) {
  69079. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69080. });
  69081. return _this;
  69082. }
  69083. return AnaglyphPostProcess;
  69084. }(BABYLON.PostProcess));
  69085. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69086. })(BABYLON || (BABYLON = {}));
  69087. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69088. var BABYLON;
  69089. (function (BABYLON) {
  69090. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69091. __extends(StereoscopicInterlacePostProcess, _super);
  69092. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69093. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69094. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69095. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69096. _this.onSizeChangedObservable.add(function () {
  69097. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69098. });
  69099. _this.onApplyObservable.add(function (effect) {
  69100. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69101. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69102. });
  69103. return _this;
  69104. }
  69105. return StereoscopicInterlacePostProcess;
  69106. }(BABYLON.PostProcess));
  69107. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69108. })(BABYLON || (BABYLON = {}));
  69109. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69110. var BABYLON;
  69111. (function (BABYLON) {
  69112. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69113. function FreeCameraDeviceOrientationInput() {
  69114. var _this = this;
  69115. this._screenOrientationAngle = 0;
  69116. this._screenQuaternion = new BABYLON.Quaternion();
  69117. this._alpha = 0;
  69118. this._beta = 0;
  69119. this._gamma = 0;
  69120. this._orientationChanged = function () {
  69121. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69122. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69123. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69124. };
  69125. this._deviceOrientation = function (evt) {
  69126. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69127. _this._beta = evt.beta !== null ? evt.beta : 0;
  69128. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69129. };
  69130. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69131. this._orientationChanged();
  69132. }
  69133. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69134. get: function () {
  69135. return this._camera;
  69136. },
  69137. set: function (camera) {
  69138. this._camera = camera;
  69139. if (this._camera != null && !this._camera.rotationQuaternion) {
  69140. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69141. }
  69142. },
  69143. enumerable: true,
  69144. configurable: true
  69145. });
  69146. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69147. window.addEventListener("orientationchange", this._orientationChanged);
  69148. window.addEventListener("deviceorientation", this._deviceOrientation);
  69149. //In certain cases, the attach control is called AFTER orientation was changed,
  69150. //So this is needed.
  69151. this._orientationChanged();
  69152. };
  69153. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69154. window.removeEventListener("orientationchange", this._orientationChanged);
  69155. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69156. };
  69157. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69158. //if no device orientation provided, don't update the rotation.
  69159. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69160. if (!this._alpha)
  69161. return;
  69162. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69163. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69164. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69165. //Mirror on XY Plane
  69166. this._camera.rotationQuaternion.z *= -1;
  69167. this._camera.rotationQuaternion.w *= -1;
  69168. };
  69169. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69170. return "FreeCameraDeviceOrientationInput";
  69171. };
  69172. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69173. return "deviceOrientation";
  69174. };
  69175. return FreeCameraDeviceOrientationInput;
  69176. }());
  69177. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69178. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69179. })(BABYLON || (BABYLON = {}));
  69180. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69181. var BABYLON;
  69182. (function (BABYLON) {
  69183. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69184. function ArcRotateCameraVRDeviceOrientationInput() {
  69185. this.alphaCorrection = 1;
  69186. this.betaCorrection = 1;
  69187. this.gammaCorrection = 1;
  69188. this._alpha = 0;
  69189. this._beta = 0;
  69190. this._gamma = 0;
  69191. this._dirty = false;
  69192. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69193. }
  69194. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69195. this.camera.attachControl(element, noPreventDefault);
  69196. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69197. };
  69198. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69199. if (evt.alpha !== null) {
  69200. this._alpha = +evt.alpha | 0;
  69201. }
  69202. if (evt.beta !== null) {
  69203. this._beta = +evt.beta | 0;
  69204. }
  69205. if (evt.gamma !== null) {
  69206. this._gamma = +evt.gamma | 0;
  69207. }
  69208. this._dirty = true;
  69209. };
  69210. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69211. if (this._dirty) {
  69212. this._dirty = false;
  69213. if (this._gamma < 0) {
  69214. this._gamma = 180 + this._gamma;
  69215. }
  69216. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69217. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69218. }
  69219. };
  69220. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69221. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69222. };
  69223. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69224. return "ArcRotateCameraVRDeviceOrientationInput";
  69225. };
  69226. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69227. return "VRDeviceOrientation";
  69228. };
  69229. return ArcRotateCameraVRDeviceOrientationInput;
  69230. }());
  69231. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69232. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69233. })(BABYLON || (BABYLON = {}));
  69234. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69235. var BABYLON;
  69236. (function (BABYLON) {
  69237. var VRCameraMetrics = /** @class */ (function () {
  69238. function VRCameraMetrics() {
  69239. this.compensateDistortion = true;
  69240. }
  69241. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69242. get: function () {
  69243. return this.hResolution / (2 * this.vResolution);
  69244. },
  69245. enumerable: true,
  69246. configurable: true
  69247. });
  69248. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69249. get: function () {
  69250. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69251. },
  69252. enumerable: true,
  69253. configurable: true
  69254. });
  69255. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69256. get: function () {
  69257. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69258. var h = (4 * meters) / this.hScreenSize;
  69259. return BABYLON.Matrix.Translation(h, 0, 0);
  69260. },
  69261. enumerable: true,
  69262. configurable: true
  69263. });
  69264. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69265. get: function () {
  69266. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69267. var h = (4 * meters) / this.hScreenSize;
  69268. return BABYLON.Matrix.Translation(-h, 0, 0);
  69269. },
  69270. enumerable: true,
  69271. configurable: true
  69272. });
  69273. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69274. get: function () {
  69275. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69276. },
  69277. enumerable: true,
  69278. configurable: true
  69279. });
  69280. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69281. get: function () {
  69282. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69283. },
  69284. enumerable: true,
  69285. configurable: true
  69286. });
  69287. VRCameraMetrics.GetDefault = function () {
  69288. var result = new VRCameraMetrics();
  69289. result.hResolution = 1280;
  69290. result.vResolution = 800;
  69291. result.hScreenSize = 0.149759993;
  69292. result.vScreenSize = 0.0935999975;
  69293. result.vScreenCenter = 0.0467999987;
  69294. result.eyeToScreenDistance = 0.0410000011;
  69295. result.lensSeparationDistance = 0.0635000020;
  69296. result.interpupillaryDistance = 0.0640000030;
  69297. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69298. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69299. result.postProcessScaleFactor = 1.714605507808412;
  69300. result.lensCenterOffset = 0.151976421;
  69301. return result;
  69302. };
  69303. return VRCameraMetrics;
  69304. }());
  69305. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69306. })(BABYLON || (BABYLON = {}));
  69307. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69308. var BABYLON;
  69309. (function (BABYLON) {
  69310. var WebVRFreeCamera = /** @class */ (function (_super) {
  69311. __extends(WebVRFreeCamera, _super);
  69312. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69313. if (webVROptions === void 0) { webVROptions = {}; }
  69314. var _this = _super.call(this, name, position, scene) || this;
  69315. _this.webVROptions = webVROptions;
  69316. _this._vrDevice = null;
  69317. _this.rawPose = null;
  69318. _this._specsVersion = "1.1";
  69319. _this._attached = false;
  69320. _this._descendants = [];
  69321. _this.devicePosition = BABYLON.Vector3.Zero();
  69322. _this.deviceScaleFactor = 1;
  69323. _this.controllers = [];
  69324. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69325. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69326. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69327. _this.minZ = 0.1;
  69328. //legacy support - the compensation boolean was removed.
  69329. if (arguments.length === 5) {
  69330. _this.webVROptions = arguments[4];
  69331. }
  69332. // default webVR options
  69333. if (_this.webVROptions.trackPosition == undefined) {
  69334. _this.webVROptions.trackPosition = true;
  69335. }
  69336. if (_this.webVROptions.controllerMeshes == undefined) {
  69337. _this.webVROptions.controllerMeshes = true;
  69338. }
  69339. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69340. _this.webVROptions.defaultLightingOnControllers = true;
  69341. }
  69342. _this.rotationQuaternion = new BABYLON.Quaternion();
  69343. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69344. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69345. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69346. }
  69347. //enable VR
  69348. var engine = _this.getEngine();
  69349. _this._onVREnabled = function (success) { if (success) {
  69350. _this.initControllers();
  69351. } };
  69352. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69353. engine.initWebVR().add(function (event) {
  69354. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69355. return;
  69356. }
  69357. _this._vrDevice = event.vrDisplay;
  69358. //reset the rig parameters.
  69359. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69360. if (_this._attached) {
  69361. _this.getEngine().enableVR();
  69362. }
  69363. });
  69364. if (typeof (VRFrameData) !== "undefined")
  69365. _this._frameData = new VRFrameData();
  69366. /**
  69367. * The idea behind the following lines:
  69368. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69369. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69370. * the second will not show it correctly.
  69371. *
  69372. * To solve this - each object that has the camera as parent will be added to a protected array.
  69373. * When the rig camera renders, it will take this array and set all of those to be its children.
  69374. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69375. * Amazing!
  69376. */
  69377. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69378. if (camera.parent === _this && _this.rigParenting) {
  69379. _this._descendants = _this.getDescendants(true, function (n) {
  69380. // don't take the cameras or the controllers!
  69381. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69382. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69383. return !isController && !isRigCamera;
  69384. });
  69385. _this._descendants.forEach(function (node) {
  69386. node.parent = camera;
  69387. });
  69388. }
  69389. });
  69390. scene.onAfterCameraRenderObservable.add(function (camera) {
  69391. if (camera.parent === _this && _this.rigParenting) {
  69392. _this._descendants.forEach(function (node) {
  69393. node.parent = _this;
  69394. });
  69395. }
  69396. });
  69397. return _this;
  69398. }
  69399. WebVRFreeCamera.prototype.dispose = function () {
  69400. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69401. _super.prototype.dispose.call(this);
  69402. };
  69403. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69404. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69405. var gp = _a[_i];
  69406. if (gp.hand === name) {
  69407. return gp;
  69408. }
  69409. }
  69410. return null;
  69411. };
  69412. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69413. get: function () {
  69414. if (!this._leftController) {
  69415. this._leftController = this.getControllerByName("left");
  69416. }
  69417. return this._leftController;
  69418. },
  69419. enumerable: true,
  69420. configurable: true
  69421. });
  69422. ;
  69423. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69424. get: function () {
  69425. if (!this._rightController) {
  69426. this._rightController = this.getControllerByName("right");
  69427. }
  69428. return this._rightController;
  69429. },
  69430. enumerable: true,
  69431. configurable: true
  69432. });
  69433. ;
  69434. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69435. if (length === void 0) { length = 100; }
  69436. if (this.leftCamera) {
  69437. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69438. }
  69439. else {
  69440. return _super.prototype.getForwardRay.call(this, length);
  69441. }
  69442. };
  69443. WebVRFreeCamera.prototype._checkInputs = function () {
  69444. if (this._vrDevice && this._vrDevice.isPresenting) {
  69445. this._vrDevice.getFrameData(this._frameData);
  69446. this.updateFromDevice(this._frameData.pose);
  69447. }
  69448. _super.prototype._checkInputs.call(this);
  69449. };
  69450. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69451. if (poseData && poseData.orientation) {
  69452. this.rawPose = poseData;
  69453. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69454. if (this.getScene().useRightHandedSystem) {
  69455. this.deviceRotationQuaternion.z *= -1;
  69456. this.deviceRotationQuaternion.w *= -1;
  69457. }
  69458. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69459. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69460. if (this.getScene().useRightHandedSystem) {
  69461. this.devicePosition.z *= -1;
  69462. }
  69463. }
  69464. }
  69465. };
  69466. /**
  69467. * WebVR's attach control will start broadcasting frames to the device.
  69468. * Note that in certain browsers (chrome for example) this function must be called
  69469. * within a user-interaction callback. Example:
  69470. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69471. *
  69472. * @param {HTMLElement} element
  69473. * @param {boolean} [noPreventDefault]
  69474. *
  69475. * @memberOf WebVRFreeCamera
  69476. */
  69477. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69478. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69479. this._attached = true;
  69480. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69481. if (this._vrDevice) {
  69482. this.getEngine().enableVR();
  69483. }
  69484. };
  69485. WebVRFreeCamera.prototype.detachControl = function (element) {
  69486. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69487. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69488. _super.prototype.detachControl.call(this, element);
  69489. this._attached = false;
  69490. this.getEngine().disableVR();
  69491. };
  69492. WebVRFreeCamera.prototype.getClassName = function () {
  69493. return "WebVRFreeCamera";
  69494. };
  69495. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69496. //uses the vrDisplay's "resetPose()".
  69497. //pitch and roll won't be affected.
  69498. this._vrDevice.resetPose();
  69499. };
  69500. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69501. var camLeft = this._rigCameras[0];
  69502. var camRight = this._rigCameras[1];
  69503. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69504. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69505. camLeft.position.copyFrom(this.devicePosition);
  69506. camRight.position.copyFrom(this.devicePosition);
  69507. };
  69508. /**
  69509. * This function is called by the two RIG cameras.
  69510. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69511. */
  69512. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69513. var _this = this;
  69514. //WebVR 1.1
  69515. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69516. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69517. if (!this.getScene().useRightHandedSystem) {
  69518. [2, 6, 8, 9, 14].forEach(function (num) {
  69519. _this._webvrViewMatrix.m[num] *= -1;
  69520. });
  69521. }
  69522. // update the camera rotation matrix
  69523. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69524. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69525. // Computing target and final matrix
  69526. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69527. var parentCamera = this._cameraRigParams["parentCamera"];
  69528. // should the view matrix be updated with scale and position offset?
  69529. if (parentCamera.deviceScaleFactor !== 1) {
  69530. this._webvrViewMatrix.invert();
  69531. // scale the position, if set
  69532. if (parentCamera.deviceScaleFactor) {
  69533. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69534. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69535. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69536. }
  69537. this._webvrViewMatrix.invert();
  69538. }
  69539. return this._webvrViewMatrix;
  69540. };
  69541. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69542. var _this = this;
  69543. var parentCamera = this.parent;
  69544. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69545. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69546. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69547. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69548. //babylon compatible matrix
  69549. if (!this.getScene().useRightHandedSystem) {
  69550. [8, 9, 10, 11].forEach(function (num) {
  69551. _this._projectionMatrix.m[num] *= -1;
  69552. });
  69553. }
  69554. return this._projectionMatrix;
  69555. };
  69556. WebVRFreeCamera.prototype.initControllers = function () {
  69557. var _this = this;
  69558. this.controllers = [];
  69559. var manager = this.getScene().gamepadManager;
  69560. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69561. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69562. var webVrController = gamepad;
  69563. if (webVrController.defaultModel) {
  69564. webVrController.defaultModel.setEnabled(false);
  69565. }
  69566. }
  69567. });
  69568. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69569. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69570. var webVrController_1 = gamepad;
  69571. if (_this.webVROptions.controllerMeshes) {
  69572. if (webVrController_1.defaultModel) {
  69573. webVrController_1.defaultModel.setEnabled(true);
  69574. }
  69575. else {
  69576. // Load the meshes
  69577. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69578. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69579. if (_this.webVROptions.defaultLightingOnControllers) {
  69580. if (!_this._lightOnControllers) {
  69581. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69582. }
  69583. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69584. var children = mesh.getChildren();
  69585. if (children.length !== 0) {
  69586. children.forEach(function (mesh) {
  69587. light.includedOnlyMeshes.push(mesh);
  69588. activateLightOnSubMeshes_1(mesh, light);
  69589. });
  69590. }
  69591. };
  69592. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69593. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69594. }
  69595. });
  69596. }
  69597. }
  69598. webVrController_1.attachToPoseControlledCamera(_this);
  69599. // since this is async - sanity check. Is the controller already stored?
  69600. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69601. //add to the controllers array
  69602. _this.controllers.push(webVrController_1);
  69603. //did we find enough controllers? Great! let the developer know.
  69604. if (_this.controllers.length >= 2) {
  69605. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69606. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69607. // So we're overriding setting left & right manually to be sure
  69608. var firstViveWandDetected = false;
  69609. for (var i = 0; i < _this.controllers.length; i++) {
  69610. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69611. if (!firstViveWandDetected) {
  69612. firstViveWandDetected = true;
  69613. _this.controllers[i].hand = "left";
  69614. }
  69615. else {
  69616. _this.controllers[i].hand = "right";
  69617. }
  69618. }
  69619. }
  69620. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69621. }
  69622. }
  69623. }
  69624. });
  69625. };
  69626. return WebVRFreeCamera;
  69627. }(BABYLON.FreeCamera));
  69628. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69629. })(BABYLON || (BABYLON = {}));
  69630. //# sourceMappingURL=babylon.webVRCamera.js.map
  69631. var BABYLON;
  69632. (function (BABYLON) {
  69633. // We're mainly based on the logic defined into the FreeCamera code
  69634. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69635. __extends(DeviceOrientationCamera, _super);
  69636. function DeviceOrientationCamera(name, position, scene) {
  69637. var _this = _super.call(this, name, position, scene) || this;
  69638. _this._quaternionCache = new BABYLON.Quaternion();
  69639. _this.inputs.addDeviceOrientation();
  69640. return _this;
  69641. }
  69642. DeviceOrientationCamera.prototype.getClassName = function () {
  69643. return "DeviceOrientationCamera";
  69644. };
  69645. DeviceOrientationCamera.prototype._checkInputs = function () {
  69646. _super.prototype._checkInputs.call(this);
  69647. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69648. if (this._initialQuaternion) {
  69649. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69650. }
  69651. };
  69652. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69653. var _this = this;
  69654. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69655. //can only work if this camera has a rotation quaternion already.
  69656. if (!this.rotationQuaternion)
  69657. return;
  69658. if (!this._initialQuaternion) {
  69659. this._initialQuaternion = new BABYLON.Quaternion();
  69660. }
  69661. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69662. ['x', 'y', 'z'].forEach(function (axisName) {
  69663. if (!axis[axisName]) {
  69664. _this._initialQuaternion[axisName] = 0;
  69665. }
  69666. else {
  69667. _this._initialQuaternion[axisName] *= -1;
  69668. }
  69669. });
  69670. this._initialQuaternion.normalize();
  69671. //force rotation update
  69672. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69673. };
  69674. return DeviceOrientationCamera;
  69675. }(BABYLON.FreeCamera));
  69676. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69677. })(BABYLON || (BABYLON = {}));
  69678. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69679. var BABYLON;
  69680. (function (BABYLON) {
  69681. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69682. __extends(VRDeviceOrientationFreeCamera, _super);
  69683. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69684. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69685. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69686. var _this = _super.call(this, name, position, scene) || this;
  69687. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69688. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69689. return _this;
  69690. }
  69691. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69692. return "VRDeviceOrientationFreeCamera";
  69693. };
  69694. return VRDeviceOrientationFreeCamera;
  69695. }(BABYLON.DeviceOrientationCamera));
  69696. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69697. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69698. __extends(VRDeviceOrientationGamepadCamera, _super);
  69699. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69700. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69701. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69702. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69703. _this.inputs.addGamepad();
  69704. return _this;
  69705. }
  69706. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69707. return "VRDeviceOrientationGamepadCamera";
  69708. };
  69709. return VRDeviceOrientationGamepadCamera;
  69710. }(VRDeviceOrientationFreeCamera));
  69711. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69712. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69713. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69714. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69715. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69716. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69717. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69718. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69719. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69720. _this.inputs.addVRDeviceOrientation();
  69721. return _this;
  69722. }
  69723. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69724. return "VRDeviceOrientationArcRotateCamera";
  69725. };
  69726. return VRDeviceOrientationArcRotateCamera;
  69727. }(BABYLON.ArcRotateCamera));
  69728. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69729. })(BABYLON || (BABYLON = {}));
  69730. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69731. var BABYLON;
  69732. (function (BABYLON) {
  69733. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69734. __extends(AnaglyphFreeCamera, _super);
  69735. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69736. var _this = _super.call(this, name, position, scene) || this;
  69737. _this.interaxialDistance = interaxialDistance;
  69738. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69739. return _this;
  69740. }
  69741. AnaglyphFreeCamera.prototype.getClassName = function () {
  69742. return "AnaglyphFreeCamera";
  69743. };
  69744. return AnaglyphFreeCamera;
  69745. }(BABYLON.FreeCamera));
  69746. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69747. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69748. __extends(AnaglyphArcRotateCamera, _super);
  69749. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69750. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69751. _this.interaxialDistance = interaxialDistance;
  69752. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69753. return _this;
  69754. }
  69755. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69756. return "AnaglyphArcRotateCamera";
  69757. };
  69758. return AnaglyphArcRotateCamera;
  69759. }(BABYLON.ArcRotateCamera));
  69760. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69761. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69762. __extends(AnaglyphGamepadCamera, _super);
  69763. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69764. var _this = _super.call(this, name, position, scene) || this;
  69765. _this.interaxialDistance = interaxialDistance;
  69766. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69767. return _this;
  69768. }
  69769. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69770. return "AnaglyphGamepadCamera";
  69771. };
  69772. return AnaglyphGamepadCamera;
  69773. }(BABYLON.GamepadCamera));
  69774. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69775. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69776. __extends(AnaglyphUniversalCamera, _super);
  69777. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69778. var _this = _super.call(this, name, position, scene) || this;
  69779. _this.interaxialDistance = interaxialDistance;
  69780. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69781. return _this;
  69782. }
  69783. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69784. return "AnaglyphUniversalCamera";
  69785. };
  69786. return AnaglyphUniversalCamera;
  69787. }(BABYLON.UniversalCamera));
  69788. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69789. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69790. __extends(StereoscopicFreeCamera, _super);
  69791. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69792. var _this = _super.call(this, name, position, scene) || this;
  69793. _this.interaxialDistance = interaxialDistance;
  69794. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69795. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69796. return _this;
  69797. }
  69798. StereoscopicFreeCamera.prototype.getClassName = function () {
  69799. return "StereoscopicFreeCamera";
  69800. };
  69801. return StereoscopicFreeCamera;
  69802. }(BABYLON.FreeCamera));
  69803. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69804. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69805. __extends(StereoscopicArcRotateCamera, _super);
  69806. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69807. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69808. _this.interaxialDistance = interaxialDistance;
  69809. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69810. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69811. return _this;
  69812. }
  69813. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69814. return "StereoscopicArcRotateCamera";
  69815. };
  69816. return StereoscopicArcRotateCamera;
  69817. }(BABYLON.ArcRotateCamera));
  69818. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69819. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69820. __extends(StereoscopicGamepadCamera, _super);
  69821. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69822. var _this = _super.call(this, name, position, scene) || this;
  69823. _this.interaxialDistance = interaxialDistance;
  69824. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69825. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69826. return _this;
  69827. }
  69828. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69829. return "StereoscopicGamepadCamera";
  69830. };
  69831. return StereoscopicGamepadCamera;
  69832. }(BABYLON.GamepadCamera));
  69833. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69834. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69835. __extends(StereoscopicUniversalCamera, _super);
  69836. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69837. var _this = _super.call(this, name, position, scene) || this;
  69838. _this.interaxialDistance = interaxialDistance;
  69839. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69840. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69841. return _this;
  69842. }
  69843. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69844. return "StereoscopicUniversalCamera";
  69845. };
  69846. return StereoscopicUniversalCamera;
  69847. }(BABYLON.UniversalCamera));
  69848. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69849. })(BABYLON || (BABYLON = {}));
  69850. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69851. var BABYLON;
  69852. (function (BABYLON) {
  69853. var VRExperienceHelper = /** @class */ (function () {
  69854. function VRExperienceHelper(scene, webVROptions) {
  69855. if (webVROptions === void 0) { webVROptions = {}; }
  69856. var _this = this;
  69857. this.webVROptions = webVROptions;
  69858. // Can the system support WebVR, even if a headset isn't plugged in?
  69859. this._webVRsupported = false;
  69860. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69861. this._webVRready = false;
  69862. // Are we waiting for the requestPresent callback to complete?
  69863. this._webVRrequesting = false;
  69864. // Are we presenting to the headset right now?
  69865. this._webVRpresenting = false;
  69866. // Are we presenting in the fullscreen fallback?
  69867. this._fullscreenVRpresenting = false;
  69868. this._scene = scene;
  69869. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69870. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69871. }
  69872. else {
  69873. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69874. if (scene.activeCamera.rotation) {
  69875. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69876. }
  69877. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69878. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69879. }
  69880. this._scene.activeCamera = this._deviceOrientationCamera;
  69881. this._position = this._scene.activeCamera.position;
  69882. this._canvas = scene.getEngine().getRenderingCanvas();
  69883. if (this._canvas) {
  69884. this._scene.activeCamera.attachControl(this._canvas);
  69885. }
  69886. this._btnVR = document.createElement("BUTTON");
  69887. this._btnVR.className = "babylonVRicon";
  69888. this._btnVR.id = "babylonVRiconbtn";
  69889. this._btnVR.title = "Click to switch to VR";
  69890. 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) }";
  69891. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69892. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69893. // css += ".babylonVRicon.vrdisplaysupported { }";
  69894. // css += ".babylonVRicon.vrdisplayready { }";
  69895. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69896. var style = document.createElement('style');
  69897. style.appendChild(document.createTextNode(css));
  69898. document.getElementsByTagName('head')[0].appendChild(style);
  69899. if (this._canvas) {
  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. this._btnVR.addEventListener("click", function () {
  69903. _this.enterVR();
  69904. });
  69905. window.addEventListener("resize", function () {
  69906. if (_this._canvas) {
  69907. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69908. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69909. }
  69910. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69911. _this.exitVR();
  69912. }
  69913. });
  69914. }
  69915. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69916. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69917. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69918. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69919. document.body.appendChild(this._btnVR);
  69920. // Exiting VR mode using 'ESC' key on desktop
  69921. this._onKeyDown = function (event) {
  69922. if (event.keyCode === 27 && _this.isInVRMode()) {
  69923. _this.exitVR();
  69924. }
  69925. };
  69926. document.addEventListener("keydown", this._onKeyDown);
  69927. // Exiting VR mode double tapping the touch screen
  69928. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69929. if (_this.isInVRMode()) {
  69930. _this.exitVR();
  69931. if (_this._fullscreenVRpresenting) {
  69932. _this._scene.getEngine().switchFullscreen(true);
  69933. }
  69934. }
  69935. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69936. // Listen for WebVR display changes
  69937. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69938. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69939. this._onVRRequestPresentStart = function () {
  69940. _this._webVRrequesting = true;
  69941. _this.updateButtonVisibility();
  69942. };
  69943. this._onVRRequestPresentComplete = function (success) {
  69944. _this._webVRrequesting = false;
  69945. _this.updateButtonVisibility();
  69946. };
  69947. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69948. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69949. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69950. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69951. // Create the cameras
  69952. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69953. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69954. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69955. this.updateButtonVisibility();
  69956. }
  69957. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69958. if (this.onControllerMeshLoaded) {
  69959. this.onControllerMeshLoaded(webVRController);
  69960. }
  69961. };
  69962. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69963. if (document.fullscreen !== undefined) {
  69964. this._fullscreenVRpresenting = document.fullscreen;
  69965. }
  69966. else if (document.mozFullScreen !== undefined) {
  69967. this._fullscreenVRpresenting = document.mozFullScreen;
  69968. }
  69969. else if (document.webkitIsFullScreen !== undefined) {
  69970. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69971. }
  69972. else if (document.msIsFullScreen !== undefined) {
  69973. this._fullscreenVRpresenting = document.msIsFullScreen;
  69974. }
  69975. if (!this._fullscreenVRpresenting && this._canvas) {
  69976. this.exitVR();
  69977. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69978. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69979. }
  69980. };
  69981. VRExperienceHelper.prototype.isInVRMode = function () {
  69982. return this._webVRpresenting || this._fullscreenVRpresenting;
  69983. };
  69984. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69985. var vrDisplay = this._scene.getEngine().getVRDevice();
  69986. if (vrDisplay) {
  69987. var wasPresenting = this._webVRpresenting;
  69988. // A VR display is connected
  69989. this._webVRpresenting = vrDisplay.isPresenting;
  69990. if (wasPresenting && !this._webVRpresenting)
  69991. this.exitVR();
  69992. }
  69993. else {
  69994. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69995. }
  69996. this.updateButtonVisibility();
  69997. };
  69998. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69999. this._webVRsupported = eventArgs.vrSupported;
  70000. this._webVRready = !!eventArgs.vrDisplay;
  70001. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  70002. this.updateButtonVisibility();
  70003. };
  70004. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  70005. if (!this._btnVR) {
  70006. return;
  70007. }
  70008. this._btnVR.className = "babylonVRicon";
  70009. if (this.isInVRMode()) {
  70010. this._btnVR.className += " vrdisplaypresenting";
  70011. }
  70012. else {
  70013. if (this._webVRready)
  70014. this._btnVR.className += " vrdisplayready";
  70015. if (this._webVRsupported)
  70016. this._btnVR.className += " vrdisplaysupported";
  70017. if (this._webVRrequesting)
  70018. this._btnVR.className += " vrdisplayrequesting";
  70019. }
  70020. };
  70021. /**
  70022. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  70023. * Otherwise, will use the fullscreen API.
  70024. */
  70025. VRExperienceHelper.prototype.enterVR = function () {
  70026. if (this.onEnteringVR) {
  70027. this.onEnteringVR();
  70028. }
  70029. if (this._webVRrequesting)
  70030. return;
  70031. // If WebVR is supported and a headset is connected
  70032. if (this._webVRready) {
  70033. if (!this._webVRpresenting) {
  70034. this._webVRCamera.position = this._position;
  70035. this._scene.activeCamera = this._webVRCamera;
  70036. }
  70037. }
  70038. else {
  70039. this._vrDeviceOrientationCamera.position = this._position;
  70040. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  70041. this._scene.getEngine().switchFullscreen(true);
  70042. this.updateButtonVisibility();
  70043. }
  70044. if (this._scene.activeCamera && this._canvas) {
  70045. this._scene.activeCamera.attachControl(this._canvas);
  70046. }
  70047. };
  70048. /**
  70049. * Attempt to exit VR, or fullscreen.
  70050. */
  70051. VRExperienceHelper.prototype.exitVR = function () {
  70052. if (this.onExitingVR) {
  70053. this.onExitingVR();
  70054. }
  70055. if (this._webVRpresenting) {
  70056. this._scene.getEngine().disableVR();
  70057. }
  70058. if (this._scene.activeCamera) {
  70059. this._position = this._scene.activeCamera.position;
  70060. }
  70061. this._deviceOrientationCamera.position = this._position;
  70062. this._scene.activeCamera = this._deviceOrientationCamera;
  70063. if (this._canvas) {
  70064. this._scene.activeCamera.attachControl(this._canvas);
  70065. }
  70066. this.updateButtonVisibility();
  70067. };
  70068. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70069. get: function () {
  70070. return this._position;
  70071. },
  70072. set: function (value) {
  70073. this._position = value;
  70074. if (this._scene.activeCamera) {
  70075. this._scene.activeCamera.position = value;
  70076. }
  70077. },
  70078. enumerable: true,
  70079. configurable: true
  70080. });
  70081. VRExperienceHelper.prototype.dispose = function () {
  70082. if (this.isInVRMode()) {
  70083. this.exitVR();
  70084. }
  70085. this._deviceOrientationCamera.dispose();
  70086. if (this._webVRCamera) {
  70087. this._webVRCamera.dispose();
  70088. }
  70089. if (this._vrDeviceOrientationCamera) {
  70090. this._vrDeviceOrientationCamera.dispose();
  70091. }
  70092. document.body.removeChild(this._btnVR);
  70093. document.removeEventListener("keydown", this._onKeyDown);
  70094. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70095. };
  70096. VRExperienceHelper.prototype.getClassName = function () {
  70097. return "VRExperienceHelper";
  70098. };
  70099. return VRExperienceHelper;
  70100. }());
  70101. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70102. })(BABYLON || (BABYLON = {}));
  70103. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70104. // Mainly based on these 2 articles :
  70105. // 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
  70106. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70107. var BABYLON;
  70108. (function (BABYLON) {
  70109. var JoystickAxis;
  70110. (function (JoystickAxis) {
  70111. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70112. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70113. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70114. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70115. var VirtualJoystick = /** @class */ (function () {
  70116. function VirtualJoystick(leftJoystick) {
  70117. var _this = this;
  70118. if (leftJoystick) {
  70119. this._leftJoystick = true;
  70120. }
  70121. else {
  70122. this._leftJoystick = false;
  70123. }
  70124. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70125. VirtualJoystick._globalJoystickIndex++;
  70126. // By default left & right arrow keys are moving the X
  70127. // and up & down keys are moving the Y
  70128. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70129. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70130. this.reverseLeftRight = false;
  70131. this.reverseUpDown = false;
  70132. // collections of pointers
  70133. this._touches = new BABYLON.StringDictionary();
  70134. this.deltaPosition = BABYLON.Vector3.Zero();
  70135. this._joystickSensibility = 25;
  70136. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70137. this._rotationSpeed = 25;
  70138. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70139. this._rotateOnAxisRelativeToMesh = false;
  70140. this._onResize = function (evt) {
  70141. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70142. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70143. if (VirtualJoystick.vjCanvas) {
  70144. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70145. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70146. }
  70147. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70148. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70149. };
  70150. // injecting a canvas element on top of the canvas 3D game
  70151. if (!VirtualJoystick.vjCanvas) {
  70152. window.addEventListener("resize", this._onResize, false);
  70153. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70154. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70155. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70156. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70157. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70158. VirtualJoystick.vjCanvas.style.width = "100%";
  70159. VirtualJoystick.vjCanvas.style.height = "100%";
  70160. VirtualJoystick.vjCanvas.style.position = "absolute";
  70161. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70162. VirtualJoystick.vjCanvas.style.top = "0px";
  70163. VirtualJoystick.vjCanvas.style.left = "0px";
  70164. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70165. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70166. // Support for jQuery PEP polyfill
  70167. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70168. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70169. if (!context) {
  70170. throw new Error("Unable to create canvas for virtual joystick");
  70171. }
  70172. VirtualJoystick.vjCanvasContext = context;
  70173. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70174. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70175. document.body.appendChild(VirtualJoystick.vjCanvas);
  70176. }
  70177. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70178. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70179. this.pressed = false;
  70180. // default joystick color
  70181. this._joystickColor = "cyan";
  70182. this._joystickPointerID = -1;
  70183. // current joystick position
  70184. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70185. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70186. // origin joystick position
  70187. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70188. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70189. this._onPointerDownHandlerRef = function (evt) {
  70190. _this._onPointerDown(evt);
  70191. };
  70192. this._onPointerMoveHandlerRef = function (evt) {
  70193. _this._onPointerMove(evt);
  70194. };
  70195. this._onPointerOutHandlerRef = function (evt) {
  70196. _this._onPointerUp(evt);
  70197. };
  70198. this._onPointerUpHandlerRef = function (evt) {
  70199. _this._onPointerUp(evt);
  70200. };
  70201. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70202. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70203. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70204. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70205. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70206. evt.preventDefault(); // Disables system menu
  70207. }, false);
  70208. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70209. }
  70210. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70211. this._joystickSensibility = newJoystickSensibility;
  70212. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70213. };
  70214. VirtualJoystick.prototype._onPointerDown = function (e) {
  70215. var positionOnScreenCondition;
  70216. e.preventDefault();
  70217. if (this._leftJoystick === true) {
  70218. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70219. }
  70220. else {
  70221. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70222. }
  70223. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70224. // First contact will be dedicated to the virtual joystick
  70225. this._joystickPointerID = e.pointerId;
  70226. this._joystickPointerStartPos.x = e.clientX;
  70227. this._joystickPointerStartPos.y = e.clientY;
  70228. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70229. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70230. this._deltaJoystickVector.x = 0;
  70231. this._deltaJoystickVector.y = 0;
  70232. this.pressed = true;
  70233. this._touches.add(e.pointerId.toString(), e);
  70234. }
  70235. else {
  70236. // You can only trigger the action buttons with a joystick declared
  70237. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70238. this._action();
  70239. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70240. }
  70241. }
  70242. };
  70243. VirtualJoystick.prototype._onPointerMove = function (e) {
  70244. // If the current pointer is the one associated to the joystick (first touch contact)
  70245. if (this._joystickPointerID == e.pointerId) {
  70246. this._joystickPointerPos.x = e.clientX;
  70247. this._joystickPointerPos.y = e.clientY;
  70248. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70249. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70250. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70251. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70252. switch (this._axisTargetedByLeftAndRight) {
  70253. case JoystickAxis.X:
  70254. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70255. break;
  70256. case JoystickAxis.Y:
  70257. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70258. break;
  70259. case JoystickAxis.Z:
  70260. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70261. break;
  70262. }
  70263. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70264. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70265. switch (this._axisTargetedByUpAndDown) {
  70266. case JoystickAxis.X:
  70267. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70268. break;
  70269. case JoystickAxis.Y:
  70270. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70271. break;
  70272. case JoystickAxis.Z:
  70273. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70274. break;
  70275. }
  70276. }
  70277. else {
  70278. var data = this._touches.get(e.pointerId.toString());
  70279. if (data) {
  70280. data.x = e.clientX;
  70281. data.y = e.clientY;
  70282. }
  70283. }
  70284. };
  70285. VirtualJoystick.prototype._onPointerUp = function (e) {
  70286. if (this._joystickPointerID == e.pointerId) {
  70287. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70288. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70289. this._joystickPointerID = -1;
  70290. this.pressed = false;
  70291. }
  70292. else {
  70293. var touch = this._touches.get(e.pointerId.toString());
  70294. if (touch) {
  70295. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70296. }
  70297. }
  70298. this._deltaJoystickVector.x = 0;
  70299. this._deltaJoystickVector.y = 0;
  70300. this._touches.remove(e.pointerId.toString());
  70301. };
  70302. /**
  70303. * Change the color of the virtual joystick
  70304. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70305. */
  70306. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70307. this._joystickColor = newColor;
  70308. };
  70309. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70310. this._action = action;
  70311. };
  70312. // Define which axis you'd like to control for left & right
  70313. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70314. switch (axis) {
  70315. case JoystickAxis.X:
  70316. case JoystickAxis.Y:
  70317. case JoystickAxis.Z:
  70318. this._axisTargetedByLeftAndRight = axis;
  70319. break;
  70320. default:
  70321. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70322. break;
  70323. }
  70324. };
  70325. // Define which axis you'd like to control for up & down
  70326. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70327. switch (axis) {
  70328. case JoystickAxis.X:
  70329. case JoystickAxis.Y:
  70330. case JoystickAxis.Z:
  70331. this._axisTargetedByUpAndDown = axis;
  70332. break;
  70333. default:
  70334. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70335. break;
  70336. }
  70337. };
  70338. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70339. var _this = this;
  70340. if (this.pressed) {
  70341. this._touches.forEach(function (key, touch) {
  70342. if (touch.pointerId === _this._joystickPointerID) {
  70343. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70344. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70345. VirtualJoystick.vjCanvasContext.beginPath();
  70346. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70347. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70348. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70349. VirtualJoystick.vjCanvasContext.stroke();
  70350. VirtualJoystick.vjCanvasContext.closePath();
  70351. VirtualJoystick.vjCanvasContext.beginPath();
  70352. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70353. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70354. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70355. VirtualJoystick.vjCanvasContext.stroke();
  70356. VirtualJoystick.vjCanvasContext.closePath();
  70357. VirtualJoystick.vjCanvasContext.beginPath();
  70358. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70359. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70360. VirtualJoystick.vjCanvasContext.stroke();
  70361. VirtualJoystick.vjCanvasContext.closePath();
  70362. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70363. }
  70364. else {
  70365. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70366. VirtualJoystick.vjCanvasContext.beginPath();
  70367. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70368. VirtualJoystick.vjCanvasContext.beginPath();
  70369. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70370. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70371. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70372. VirtualJoystick.vjCanvasContext.stroke();
  70373. VirtualJoystick.vjCanvasContext.closePath();
  70374. touch.prevX = touch.x;
  70375. touch.prevY = touch.y;
  70376. }
  70377. ;
  70378. });
  70379. }
  70380. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70381. };
  70382. VirtualJoystick.prototype.releaseCanvas = function () {
  70383. if (VirtualJoystick.vjCanvas) {
  70384. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70385. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70386. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70387. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70388. window.removeEventListener("resize", this._onResize);
  70389. document.body.removeChild(VirtualJoystick.vjCanvas);
  70390. VirtualJoystick.vjCanvas = null;
  70391. }
  70392. };
  70393. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70394. VirtualJoystick._globalJoystickIndex = 0;
  70395. return VirtualJoystick;
  70396. }());
  70397. BABYLON.VirtualJoystick = VirtualJoystick;
  70398. })(BABYLON || (BABYLON = {}));
  70399. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70400. var BABYLON;
  70401. (function (BABYLON) {
  70402. // We're mainly based on the logic defined into the FreeCamera code
  70403. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70404. __extends(VirtualJoysticksCamera, _super);
  70405. function VirtualJoysticksCamera(name, position, scene) {
  70406. var _this = _super.call(this, name, position, scene) || this;
  70407. _this.inputs.addVirtualJoystick();
  70408. return _this;
  70409. }
  70410. VirtualJoysticksCamera.prototype.getClassName = function () {
  70411. return "VirtualJoysticksCamera";
  70412. };
  70413. return VirtualJoysticksCamera;
  70414. }(BABYLON.FreeCamera));
  70415. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70416. })(BABYLON || (BABYLON = {}));
  70417. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70418. var BABYLON;
  70419. (function (BABYLON) {
  70420. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70421. function FreeCameraVirtualJoystickInput() {
  70422. }
  70423. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70424. return this._leftjoystick;
  70425. };
  70426. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70427. return this._rightjoystick;
  70428. };
  70429. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70430. if (this._leftjoystick) {
  70431. var camera = this.camera;
  70432. var speed = camera._computeLocalCameraSpeed() * 50;
  70433. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70434. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70435. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70436. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70437. if (!this._leftjoystick.pressed) {
  70438. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70439. }
  70440. if (!this._rightjoystick.pressed) {
  70441. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70442. }
  70443. }
  70444. };
  70445. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70446. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70447. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70448. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70449. this._leftjoystick.setJoystickSensibility(0.15);
  70450. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70451. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70452. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70453. this._rightjoystick.reverseUpDown = true;
  70454. this._rightjoystick.setJoystickSensibility(0.05);
  70455. this._rightjoystick.setJoystickColor("yellow");
  70456. };
  70457. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70458. this._leftjoystick.releaseCanvas();
  70459. this._rightjoystick.releaseCanvas();
  70460. };
  70461. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70462. return "FreeCameraVirtualJoystickInput";
  70463. };
  70464. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70465. return "virtualJoystick";
  70466. };
  70467. return FreeCameraVirtualJoystickInput;
  70468. }());
  70469. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70470. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70471. })(BABYLON || (BABYLON = {}));
  70472. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70473. var BABYLON;
  70474. (function (BABYLON) {
  70475. var SimplificationSettings = /** @class */ (function () {
  70476. function SimplificationSettings(quality, distance, optimizeMesh) {
  70477. this.quality = quality;
  70478. this.distance = distance;
  70479. this.optimizeMesh = optimizeMesh;
  70480. }
  70481. return SimplificationSettings;
  70482. }());
  70483. BABYLON.SimplificationSettings = SimplificationSettings;
  70484. var SimplificationQueue = /** @class */ (function () {
  70485. function SimplificationQueue() {
  70486. this.running = false;
  70487. this._simplificationArray = [];
  70488. }
  70489. SimplificationQueue.prototype.addTask = function (task) {
  70490. this._simplificationArray.push(task);
  70491. };
  70492. SimplificationQueue.prototype.executeNext = function () {
  70493. var task = this._simplificationArray.pop();
  70494. if (task) {
  70495. this.running = true;
  70496. this.runSimplification(task);
  70497. }
  70498. else {
  70499. this.running = false;
  70500. }
  70501. };
  70502. SimplificationQueue.prototype.runSimplification = function (task) {
  70503. var _this = this;
  70504. if (task.parallelProcessing) {
  70505. //parallel simplifier
  70506. task.settings.forEach(function (setting) {
  70507. var simplifier = _this.getSimplifier(task);
  70508. simplifier.simplify(setting, function (newMesh) {
  70509. task.mesh.addLODLevel(setting.distance, newMesh);
  70510. newMesh.isVisible = true;
  70511. //check if it is the last
  70512. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70513. //all done, run the success callback.
  70514. task.successCallback();
  70515. }
  70516. _this.executeNext();
  70517. });
  70518. });
  70519. }
  70520. else {
  70521. //single simplifier.
  70522. var simplifier = this.getSimplifier(task);
  70523. var runDecimation = function (setting, callback) {
  70524. simplifier.simplify(setting, function (newMesh) {
  70525. task.mesh.addLODLevel(setting.distance, newMesh);
  70526. newMesh.isVisible = true;
  70527. //run the next quality level
  70528. callback();
  70529. });
  70530. };
  70531. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70532. runDecimation(task.settings[loop.index], function () {
  70533. loop.executeNext();
  70534. });
  70535. }, function () {
  70536. //execution ended, run the success callback.
  70537. if (task.successCallback) {
  70538. task.successCallback();
  70539. }
  70540. _this.executeNext();
  70541. });
  70542. }
  70543. };
  70544. SimplificationQueue.prototype.getSimplifier = function (task) {
  70545. switch (task.simplificationType) {
  70546. case SimplificationType.QUADRATIC:
  70547. default:
  70548. return new QuadraticErrorSimplification(task.mesh);
  70549. }
  70550. };
  70551. return SimplificationQueue;
  70552. }());
  70553. BABYLON.SimplificationQueue = SimplificationQueue;
  70554. /**
  70555. * The implemented types of simplification.
  70556. * At the moment only Quadratic Error Decimation is implemented.
  70557. */
  70558. var SimplificationType;
  70559. (function (SimplificationType) {
  70560. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70561. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70562. var DecimationTriangle = /** @class */ (function () {
  70563. function DecimationTriangle(vertices) {
  70564. this.vertices = vertices;
  70565. this.error = new Array(4);
  70566. this.deleted = false;
  70567. this.isDirty = false;
  70568. this.deletePending = false;
  70569. this.borderFactor = 0;
  70570. }
  70571. return DecimationTriangle;
  70572. }());
  70573. BABYLON.DecimationTriangle = DecimationTriangle;
  70574. var DecimationVertex = /** @class */ (function () {
  70575. function DecimationVertex(position, id) {
  70576. this.position = position;
  70577. this.id = id;
  70578. this.isBorder = true;
  70579. this.q = new QuadraticMatrix();
  70580. this.triangleCount = 0;
  70581. this.triangleStart = 0;
  70582. this.originalOffsets = [];
  70583. }
  70584. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70585. this.position.copyFrom(newPosition);
  70586. };
  70587. return DecimationVertex;
  70588. }());
  70589. BABYLON.DecimationVertex = DecimationVertex;
  70590. var QuadraticMatrix = /** @class */ (function () {
  70591. function QuadraticMatrix(data) {
  70592. this.data = new Array(10);
  70593. for (var i = 0; i < 10; ++i) {
  70594. if (data && data[i]) {
  70595. this.data[i] = data[i];
  70596. }
  70597. else {
  70598. this.data[i] = 0;
  70599. }
  70600. }
  70601. }
  70602. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70603. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70604. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70605. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70606. return det;
  70607. };
  70608. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70609. for (var i = 0; i < 10; ++i) {
  70610. this.data[i] += matrix.data[i];
  70611. }
  70612. };
  70613. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70614. for (var i = 0; i < 10; ++i) {
  70615. this.data[i] += data[i];
  70616. }
  70617. };
  70618. QuadraticMatrix.prototype.add = function (matrix) {
  70619. var m = new QuadraticMatrix();
  70620. for (var i = 0; i < 10; ++i) {
  70621. m.data[i] = this.data[i] + matrix.data[i];
  70622. }
  70623. return m;
  70624. };
  70625. QuadraticMatrix.FromData = function (a, b, c, d) {
  70626. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70627. };
  70628. //returning an array to avoid garbage collection
  70629. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70630. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70631. };
  70632. return QuadraticMatrix;
  70633. }());
  70634. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70635. var Reference = /** @class */ (function () {
  70636. function Reference(vertexId, triangleId) {
  70637. this.vertexId = vertexId;
  70638. this.triangleId = triangleId;
  70639. }
  70640. return Reference;
  70641. }());
  70642. BABYLON.Reference = Reference;
  70643. /**
  70644. * An implementation of the Quadratic Error simplification algorithm.
  70645. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70646. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70647. * @author RaananW
  70648. */
  70649. var QuadraticErrorSimplification = /** @class */ (function () {
  70650. function QuadraticErrorSimplification(_mesh) {
  70651. this._mesh = _mesh;
  70652. this.initialized = false;
  70653. this.syncIterations = 5000;
  70654. this.aggressiveness = 7;
  70655. this.decimationIterations = 100;
  70656. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70657. }
  70658. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70659. var _this = this;
  70660. this.initDecimatedMesh();
  70661. //iterating through the submeshes array, one after the other.
  70662. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70663. _this.initWithMesh(loop.index, function () {
  70664. _this.runDecimation(settings, loop.index, function () {
  70665. loop.executeNext();
  70666. });
  70667. }, settings.optimizeMesh);
  70668. }, function () {
  70669. setTimeout(function () {
  70670. successCallback(_this._reconstructedMesh);
  70671. }, 0);
  70672. });
  70673. };
  70674. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70675. var _this = this;
  70676. var targetCount = ~~(this.triangles.length * settings.quality);
  70677. var deletedTriangles = 0;
  70678. var triangleCount = this.triangles.length;
  70679. var iterationFunction = function (iteration, callback) {
  70680. setTimeout(function () {
  70681. if (iteration % 5 === 0) {
  70682. _this.updateMesh(iteration === 0);
  70683. }
  70684. for (var i = 0; i < _this.triangles.length; ++i) {
  70685. _this.triangles[i].isDirty = false;
  70686. }
  70687. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70688. var trianglesIterator = function (i) {
  70689. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70690. var t = _this.triangles[tIdx];
  70691. if (!t)
  70692. return;
  70693. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70694. return;
  70695. }
  70696. for (var j = 0; j < 3; ++j) {
  70697. if (t.error[j] < threshold) {
  70698. var deleted0 = [];
  70699. var deleted1 = [];
  70700. var v0 = t.vertices[j];
  70701. var v1 = t.vertices[(j + 1) % 3];
  70702. if (v0.isBorder || v1.isBorder)
  70703. continue;
  70704. var p = BABYLON.Vector3.Zero();
  70705. var n = BABYLON.Vector3.Zero();
  70706. var uv = BABYLON.Vector2.Zero();
  70707. var color = new BABYLON.Color4(0, 0, 0, 1);
  70708. _this.calculateError(v0, v1, p, n, uv, color);
  70709. var delTr = new Array();
  70710. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70711. continue;
  70712. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70713. continue;
  70714. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70715. continue;
  70716. var uniqueArray = new Array();
  70717. delTr.forEach(function (deletedT) {
  70718. if (uniqueArray.indexOf(deletedT) === -1) {
  70719. deletedT.deletePending = true;
  70720. uniqueArray.push(deletedT);
  70721. }
  70722. });
  70723. if (uniqueArray.length % 2 !== 0) {
  70724. continue;
  70725. }
  70726. v0.q = v1.q.add(v0.q);
  70727. v0.updatePosition(p);
  70728. var tStart = _this.references.length;
  70729. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70730. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70731. var tCount = _this.references.length - tStart;
  70732. if (tCount <= v0.triangleCount) {
  70733. if (tCount) {
  70734. for (var c = 0; c < tCount; c++) {
  70735. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70736. }
  70737. }
  70738. }
  70739. else {
  70740. v0.triangleStart = tStart;
  70741. }
  70742. v0.triangleCount = tCount;
  70743. break;
  70744. }
  70745. }
  70746. };
  70747. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70748. }, 0);
  70749. };
  70750. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70751. if (triangleCount - deletedTriangles <= targetCount)
  70752. loop.breakLoop();
  70753. else {
  70754. iterationFunction(loop.index, function () {
  70755. loop.executeNext();
  70756. });
  70757. }
  70758. }, function () {
  70759. setTimeout(function () {
  70760. //reconstruct this part of the mesh
  70761. _this.reconstructMesh(submeshIndex);
  70762. successCallback();
  70763. }, 0);
  70764. });
  70765. };
  70766. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70767. var _this = this;
  70768. this.vertices = [];
  70769. this.triangles = [];
  70770. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70771. var indices = this._mesh.getIndices();
  70772. var submesh = this._mesh.subMeshes[submeshIndex];
  70773. var findInVertices = function (positionToSearch) {
  70774. if (optimizeMesh) {
  70775. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70776. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70777. return _this.vertices[ii];
  70778. }
  70779. }
  70780. }
  70781. return null;
  70782. };
  70783. var vertexReferences = [];
  70784. var vertexInit = function (i) {
  70785. if (!positionData) {
  70786. return;
  70787. }
  70788. var offset = i + submesh.verticesStart;
  70789. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70790. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70791. vertex.originalOffsets.push(offset);
  70792. if (vertex.id === _this.vertices.length) {
  70793. _this.vertices.push(vertex);
  70794. }
  70795. vertexReferences.push(vertex.id);
  70796. };
  70797. //var totalVertices = mesh.getTotalVertices();
  70798. var totalVertices = submesh.verticesCount;
  70799. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70800. var indicesInit = function (i) {
  70801. if (!indices) {
  70802. return;
  70803. }
  70804. var offset = (submesh.indexStart / 3) + i;
  70805. var pos = (offset * 3);
  70806. var i0 = indices[pos + 0];
  70807. var i1 = indices[pos + 1];
  70808. var i2 = indices[pos + 2];
  70809. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70810. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70811. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70812. var triangle = new DecimationTriangle([v0, v1, v2]);
  70813. triangle.originalOffset = pos;
  70814. _this.triangles.push(triangle);
  70815. };
  70816. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70817. _this.init(callback);
  70818. });
  70819. });
  70820. };
  70821. QuadraticErrorSimplification.prototype.init = function (callback) {
  70822. var _this = this;
  70823. var triangleInit1 = function (i) {
  70824. var t = _this.triangles[i];
  70825. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70826. for (var j = 0; j < 3; j++) {
  70827. 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))));
  70828. }
  70829. };
  70830. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70831. var triangleInit2 = function (i) {
  70832. var t = _this.triangles[i];
  70833. for (var j = 0; j < 3; ++j) {
  70834. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70835. }
  70836. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70837. };
  70838. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70839. _this.initialized = true;
  70840. callback();
  70841. });
  70842. });
  70843. };
  70844. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70845. var newTriangles = [];
  70846. var i;
  70847. for (i = 0; i < this.vertices.length; ++i) {
  70848. this.vertices[i].triangleCount = 0;
  70849. }
  70850. var t;
  70851. var j;
  70852. for (i = 0; i < this.triangles.length; ++i) {
  70853. if (!this.triangles[i].deleted) {
  70854. t = this.triangles[i];
  70855. for (j = 0; j < 3; ++j) {
  70856. t.vertices[j].triangleCount = 1;
  70857. }
  70858. newTriangles.push(t);
  70859. }
  70860. }
  70861. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70862. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70863. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70864. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70865. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70866. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70867. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70868. var vertexCount = 0;
  70869. for (i = 0; i < this.vertices.length; ++i) {
  70870. var vertex = this.vertices[i];
  70871. vertex.id = vertexCount;
  70872. if (vertex.triangleCount) {
  70873. vertex.originalOffsets.forEach(function (originalOffset) {
  70874. if (!normalData) {
  70875. return;
  70876. }
  70877. newPositionData.push(vertex.position.x);
  70878. newPositionData.push(vertex.position.y);
  70879. newPositionData.push(vertex.position.z);
  70880. newNormalData.push(normalData[originalOffset * 3]);
  70881. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70882. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70883. if (uvs && uvs.length) {
  70884. newUVsData.push(uvs[(originalOffset * 2)]);
  70885. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70886. }
  70887. else if (colorsData && colorsData.length) {
  70888. newColorsData.push(colorsData[(originalOffset * 4)]);
  70889. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70890. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70891. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70892. }
  70893. ++vertexCount;
  70894. });
  70895. }
  70896. }
  70897. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70898. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70899. var submeshesArray = this._reconstructedMesh.subMeshes;
  70900. this._reconstructedMesh.subMeshes = [];
  70901. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70902. var originalIndices = this._mesh.getIndices();
  70903. for (i = 0; i < newTriangles.length; ++i) {
  70904. t = newTriangles[i]; //now get the new referencing point for each vertex
  70905. [0, 1, 2].forEach(function (idx) {
  70906. var id = originalIndices[t.originalOffset + idx];
  70907. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70908. if (offset < 0)
  70909. offset = 0;
  70910. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70911. });
  70912. }
  70913. //overwriting the old vertex buffers and indices.
  70914. this._reconstructedMesh.setIndices(newIndicesArray);
  70915. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70916. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70917. if (newUVsData.length > 0)
  70918. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70919. if (newColorsData.length > 0)
  70920. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70921. //create submesh
  70922. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70923. if (submeshIndex > 0) {
  70924. this._reconstructedMesh.subMeshes = [];
  70925. submeshesArray.forEach(function (submesh) {
  70926. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70927. });
  70928. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70929. }
  70930. };
  70931. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70932. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70933. this._reconstructedMesh.material = this._mesh.material;
  70934. this._reconstructedMesh.parent = this._mesh.parent;
  70935. this._reconstructedMesh.isVisible = false;
  70936. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70937. };
  70938. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70939. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70940. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70941. if (t.deleted)
  70942. continue;
  70943. var s = this.references[vertex1.triangleStart + i].vertexId;
  70944. var v1 = t.vertices[(s + 1) % 3];
  70945. var v2 = t.vertices[(s + 2) % 3];
  70946. if ((v1 === vertex2 || v2 === vertex2)) {
  70947. deletedArray[i] = true;
  70948. delTr.push(t);
  70949. continue;
  70950. }
  70951. var d1 = v1.position.subtract(point);
  70952. d1 = d1.normalize();
  70953. var d2 = v2.position.subtract(point);
  70954. d2 = d2.normalize();
  70955. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70956. return true;
  70957. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70958. deletedArray[i] = false;
  70959. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70960. return true;
  70961. }
  70962. return false;
  70963. };
  70964. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70965. var newDeleted = deletedTriangles;
  70966. for (var i = 0; i < vertex.triangleCount; ++i) {
  70967. var ref = this.references[vertex.triangleStart + i];
  70968. var t = this.triangles[ref.triangleId];
  70969. if (t.deleted)
  70970. continue;
  70971. if (deletedArray[i] && t.deletePending) {
  70972. t.deleted = true;
  70973. newDeleted++;
  70974. continue;
  70975. }
  70976. t.vertices[ref.vertexId] = origVertex;
  70977. t.isDirty = true;
  70978. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70979. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70980. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70981. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70982. this.references.push(ref);
  70983. }
  70984. return newDeleted;
  70985. };
  70986. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70987. for (var i = 0; i < this.vertices.length; ++i) {
  70988. var vCount = [];
  70989. var vId = [];
  70990. var v = this.vertices[i];
  70991. var j;
  70992. for (j = 0; j < v.triangleCount; ++j) {
  70993. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70994. for (var ii = 0; ii < 3; ii++) {
  70995. var ofs = 0;
  70996. var vv = triangle.vertices[ii];
  70997. while (ofs < vCount.length) {
  70998. if (vId[ofs] === vv.id)
  70999. break;
  71000. ++ofs;
  71001. }
  71002. if (ofs === vCount.length) {
  71003. vCount.push(1);
  71004. vId.push(vv.id);
  71005. }
  71006. else {
  71007. vCount[ofs]++;
  71008. }
  71009. }
  71010. }
  71011. for (j = 0; j < vCount.length; ++j) {
  71012. if (vCount[j] === 1) {
  71013. this.vertices[vId[j]].isBorder = true;
  71014. }
  71015. else {
  71016. this.vertices[vId[j]].isBorder = false;
  71017. }
  71018. }
  71019. }
  71020. };
  71021. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  71022. if (identifyBorders === void 0) { identifyBorders = false; }
  71023. var i;
  71024. if (!identifyBorders) {
  71025. var newTrianglesVector = [];
  71026. for (i = 0; i < this.triangles.length; ++i) {
  71027. if (!this.triangles[i].deleted) {
  71028. newTrianglesVector.push(this.triangles[i]);
  71029. }
  71030. }
  71031. this.triangles = newTrianglesVector;
  71032. }
  71033. for (i = 0; i < this.vertices.length; ++i) {
  71034. this.vertices[i].triangleCount = 0;
  71035. this.vertices[i].triangleStart = 0;
  71036. }
  71037. var t;
  71038. var j;
  71039. var v;
  71040. for (i = 0; i < this.triangles.length; ++i) {
  71041. t = this.triangles[i];
  71042. for (j = 0; j < 3; ++j) {
  71043. v = t.vertices[j];
  71044. v.triangleCount++;
  71045. }
  71046. }
  71047. var tStart = 0;
  71048. for (i = 0; i < this.vertices.length; ++i) {
  71049. this.vertices[i].triangleStart = tStart;
  71050. tStart += this.vertices[i].triangleCount;
  71051. this.vertices[i].triangleCount = 0;
  71052. }
  71053. var newReferences = new Array(this.triangles.length * 3);
  71054. for (i = 0; i < this.triangles.length; ++i) {
  71055. t = this.triangles[i];
  71056. for (j = 0; j < 3; ++j) {
  71057. v = t.vertices[j];
  71058. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  71059. v.triangleCount++;
  71060. }
  71061. }
  71062. this.references = newReferences;
  71063. if (identifyBorders) {
  71064. this.identifyBorder();
  71065. }
  71066. };
  71067. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  71068. var x = point.x;
  71069. var y = point.y;
  71070. var z = point.z;
  71071. 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
  71072. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  71073. };
  71074. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  71075. var q = vertex1.q.add(vertex2.q);
  71076. var border = vertex1.isBorder && vertex2.isBorder;
  71077. var error = 0;
  71078. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71079. if (qDet !== 0 && !border) {
  71080. if (!pointResult) {
  71081. pointResult = BABYLON.Vector3.Zero();
  71082. }
  71083. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71084. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71085. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71086. error = this.vertexError(q, pointResult);
  71087. }
  71088. else {
  71089. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71090. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71091. var error1 = this.vertexError(q, vertex1.position);
  71092. var error2 = this.vertexError(q, vertex2.position);
  71093. var error3 = this.vertexError(q, p3);
  71094. error = Math.min(error1, error2, error3);
  71095. if (error === error1) {
  71096. if (pointResult) {
  71097. pointResult.copyFrom(vertex1.position);
  71098. }
  71099. }
  71100. else if (error === error2) {
  71101. if (pointResult) {
  71102. pointResult.copyFrom(vertex2.position);
  71103. }
  71104. }
  71105. else {
  71106. if (pointResult) {
  71107. pointResult.copyFrom(p3);
  71108. }
  71109. }
  71110. }
  71111. return error;
  71112. };
  71113. return QuadraticErrorSimplification;
  71114. }());
  71115. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71116. })(BABYLON || (BABYLON = {}));
  71117. //# sourceMappingURL=babylon.meshSimplification.js.map
  71118. var BABYLON;
  71119. (function (BABYLON) {
  71120. var Internals;
  71121. (function (Internals) {
  71122. var MeshLODLevel = /** @class */ (function () {
  71123. function MeshLODLevel(distance, mesh) {
  71124. this.distance = distance;
  71125. this.mesh = mesh;
  71126. }
  71127. return MeshLODLevel;
  71128. }());
  71129. Internals.MeshLODLevel = MeshLODLevel;
  71130. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71131. })(BABYLON || (BABYLON = {}));
  71132. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71133. var BABYLON;
  71134. (function (BABYLON) {
  71135. // Standard optimizations
  71136. var SceneOptimization = /** @class */ (function () {
  71137. function SceneOptimization(priority) {
  71138. if (priority === void 0) { priority = 0; }
  71139. this.priority = priority;
  71140. this.apply = function (scene) {
  71141. return true; // Return true if everything that can be done was applied
  71142. };
  71143. }
  71144. return SceneOptimization;
  71145. }());
  71146. BABYLON.SceneOptimization = SceneOptimization;
  71147. var TextureOptimization = /** @class */ (function (_super) {
  71148. __extends(TextureOptimization, _super);
  71149. function TextureOptimization(priority, maximumSize) {
  71150. if (priority === void 0) { priority = 0; }
  71151. if (maximumSize === void 0) { maximumSize = 1024; }
  71152. var _this = _super.call(this, priority) || this;
  71153. _this.priority = priority;
  71154. _this.maximumSize = maximumSize;
  71155. _this.apply = function (scene) {
  71156. var allDone = true;
  71157. for (var index = 0; index < scene.textures.length; index++) {
  71158. var texture = scene.textures[index];
  71159. if (!texture.canRescale || texture.getContext) {
  71160. continue;
  71161. }
  71162. var currentSize = texture.getSize();
  71163. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71164. if (maxDimension > _this.maximumSize) {
  71165. texture.scale(0.5);
  71166. allDone = false;
  71167. }
  71168. }
  71169. return allDone;
  71170. };
  71171. return _this;
  71172. }
  71173. return TextureOptimization;
  71174. }(SceneOptimization));
  71175. BABYLON.TextureOptimization = TextureOptimization;
  71176. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71177. __extends(HardwareScalingOptimization, _super);
  71178. function HardwareScalingOptimization(priority, maximumScale) {
  71179. if (priority === void 0) { priority = 0; }
  71180. if (maximumScale === void 0) { maximumScale = 2; }
  71181. var _this = _super.call(this, priority) || this;
  71182. _this.priority = priority;
  71183. _this.maximumScale = maximumScale;
  71184. _this._currentScale = 1;
  71185. _this.apply = function (scene) {
  71186. _this._currentScale++;
  71187. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71188. return _this._currentScale >= _this.maximumScale;
  71189. };
  71190. return _this;
  71191. }
  71192. return HardwareScalingOptimization;
  71193. }(SceneOptimization));
  71194. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71195. var ShadowsOptimization = /** @class */ (function (_super) {
  71196. __extends(ShadowsOptimization, _super);
  71197. function ShadowsOptimization() {
  71198. var _this = _super !== null && _super.apply(this, arguments) || this;
  71199. _this.apply = function (scene) {
  71200. scene.shadowsEnabled = false;
  71201. return true;
  71202. };
  71203. return _this;
  71204. }
  71205. return ShadowsOptimization;
  71206. }(SceneOptimization));
  71207. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71208. var PostProcessesOptimization = /** @class */ (function (_super) {
  71209. __extends(PostProcessesOptimization, _super);
  71210. function PostProcessesOptimization() {
  71211. var _this = _super !== null && _super.apply(this, arguments) || this;
  71212. _this.apply = function (scene) {
  71213. scene.postProcessesEnabled = false;
  71214. return true;
  71215. };
  71216. return _this;
  71217. }
  71218. return PostProcessesOptimization;
  71219. }(SceneOptimization));
  71220. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71221. var LensFlaresOptimization = /** @class */ (function (_super) {
  71222. __extends(LensFlaresOptimization, _super);
  71223. function LensFlaresOptimization() {
  71224. var _this = _super !== null && _super.apply(this, arguments) || this;
  71225. _this.apply = function (scene) {
  71226. scene.lensFlaresEnabled = false;
  71227. return true;
  71228. };
  71229. return _this;
  71230. }
  71231. return LensFlaresOptimization;
  71232. }(SceneOptimization));
  71233. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71234. var ParticlesOptimization = /** @class */ (function (_super) {
  71235. __extends(ParticlesOptimization, _super);
  71236. function ParticlesOptimization() {
  71237. var _this = _super !== null && _super.apply(this, arguments) || this;
  71238. _this.apply = function (scene) {
  71239. scene.particlesEnabled = false;
  71240. return true;
  71241. };
  71242. return _this;
  71243. }
  71244. return ParticlesOptimization;
  71245. }(SceneOptimization));
  71246. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71247. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71248. __extends(RenderTargetsOptimization, _super);
  71249. function RenderTargetsOptimization() {
  71250. var _this = _super !== null && _super.apply(this, arguments) || this;
  71251. _this.apply = function (scene) {
  71252. scene.renderTargetsEnabled = false;
  71253. return true;
  71254. };
  71255. return _this;
  71256. }
  71257. return RenderTargetsOptimization;
  71258. }(SceneOptimization));
  71259. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71260. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71261. __extends(MergeMeshesOptimization, _super);
  71262. function MergeMeshesOptimization() {
  71263. var _this = _super !== null && _super.apply(this, arguments) || this;
  71264. _this._canBeMerged = function (abstractMesh) {
  71265. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71266. return false;
  71267. }
  71268. var mesh = abstractMesh;
  71269. if (!mesh.isVisible || !mesh.isEnabled()) {
  71270. return false;
  71271. }
  71272. if (mesh.instances.length > 0) {
  71273. return false;
  71274. }
  71275. if (mesh.skeleton || mesh.hasLODLevels) {
  71276. return false;
  71277. }
  71278. if (mesh.parent) {
  71279. return false;
  71280. }
  71281. return true;
  71282. };
  71283. _this.apply = function (scene, updateSelectionTree) {
  71284. var globalPool = scene.meshes.slice(0);
  71285. var globalLength = globalPool.length;
  71286. for (var index = 0; index < globalLength; index++) {
  71287. var currentPool = new Array();
  71288. var current = globalPool[index];
  71289. // Checks
  71290. if (!_this._canBeMerged(current)) {
  71291. continue;
  71292. }
  71293. currentPool.push(current);
  71294. // Find compatible meshes
  71295. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71296. var otherMesh = globalPool[subIndex];
  71297. if (!_this._canBeMerged(otherMesh)) {
  71298. continue;
  71299. }
  71300. if (otherMesh.material !== current.material) {
  71301. continue;
  71302. }
  71303. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71304. continue;
  71305. }
  71306. currentPool.push(otherMesh);
  71307. globalLength--;
  71308. globalPool.splice(subIndex, 1);
  71309. subIndex--;
  71310. }
  71311. if (currentPool.length < 2) {
  71312. continue;
  71313. }
  71314. // Merge meshes
  71315. BABYLON.Mesh.MergeMeshes(currentPool);
  71316. }
  71317. if (updateSelectionTree != undefined) {
  71318. if (updateSelectionTree) {
  71319. scene.createOrUpdateSelectionOctree();
  71320. }
  71321. }
  71322. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71323. scene.createOrUpdateSelectionOctree();
  71324. }
  71325. return true;
  71326. };
  71327. return _this;
  71328. }
  71329. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71330. get: function () {
  71331. return MergeMeshesOptimization._UpdateSelectionTree;
  71332. },
  71333. set: function (value) {
  71334. MergeMeshesOptimization._UpdateSelectionTree = value;
  71335. },
  71336. enumerable: true,
  71337. configurable: true
  71338. });
  71339. MergeMeshesOptimization._UpdateSelectionTree = false;
  71340. return MergeMeshesOptimization;
  71341. }(SceneOptimization));
  71342. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71343. // Options
  71344. var SceneOptimizerOptions = /** @class */ (function () {
  71345. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71346. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71347. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71348. this.targetFrameRate = targetFrameRate;
  71349. this.trackerDuration = trackerDuration;
  71350. this.optimizations = new Array();
  71351. }
  71352. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71353. var result = new SceneOptimizerOptions(targetFrameRate);
  71354. var priority = 0;
  71355. result.optimizations.push(new MergeMeshesOptimization(priority));
  71356. result.optimizations.push(new ShadowsOptimization(priority));
  71357. result.optimizations.push(new LensFlaresOptimization(priority));
  71358. // Next priority
  71359. priority++;
  71360. result.optimizations.push(new PostProcessesOptimization(priority));
  71361. result.optimizations.push(new ParticlesOptimization(priority));
  71362. // Next priority
  71363. priority++;
  71364. result.optimizations.push(new TextureOptimization(priority, 1024));
  71365. return result;
  71366. };
  71367. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71368. var result = new SceneOptimizerOptions(targetFrameRate);
  71369. var priority = 0;
  71370. result.optimizations.push(new MergeMeshesOptimization(priority));
  71371. result.optimizations.push(new ShadowsOptimization(priority));
  71372. result.optimizations.push(new LensFlaresOptimization(priority));
  71373. // Next priority
  71374. priority++;
  71375. result.optimizations.push(new PostProcessesOptimization(priority));
  71376. result.optimizations.push(new ParticlesOptimization(priority));
  71377. // Next priority
  71378. priority++;
  71379. result.optimizations.push(new TextureOptimization(priority, 512));
  71380. // Next priority
  71381. priority++;
  71382. result.optimizations.push(new RenderTargetsOptimization(priority));
  71383. // Next priority
  71384. priority++;
  71385. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71386. return result;
  71387. };
  71388. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71389. var result = new SceneOptimizerOptions(targetFrameRate);
  71390. var priority = 0;
  71391. result.optimizations.push(new MergeMeshesOptimization(priority));
  71392. result.optimizations.push(new ShadowsOptimization(priority));
  71393. result.optimizations.push(new LensFlaresOptimization(priority));
  71394. // Next priority
  71395. priority++;
  71396. result.optimizations.push(new PostProcessesOptimization(priority));
  71397. result.optimizations.push(new ParticlesOptimization(priority));
  71398. // Next priority
  71399. priority++;
  71400. result.optimizations.push(new TextureOptimization(priority, 256));
  71401. // Next priority
  71402. priority++;
  71403. result.optimizations.push(new RenderTargetsOptimization(priority));
  71404. // Next priority
  71405. priority++;
  71406. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71407. return result;
  71408. };
  71409. return SceneOptimizerOptions;
  71410. }());
  71411. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71412. // Scene optimizer tool
  71413. var SceneOptimizer = /** @class */ (function () {
  71414. function SceneOptimizer() {
  71415. }
  71416. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71417. // TODO: add an epsilon
  71418. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71419. if (onSuccess) {
  71420. onSuccess();
  71421. }
  71422. return;
  71423. }
  71424. // Apply current level of optimizations
  71425. var allDone = true;
  71426. var noOptimizationApplied = true;
  71427. for (var index = 0; index < options.optimizations.length; index++) {
  71428. var optimization = options.optimizations[index];
  71429. if (optimization.priority === currentPriorityLevel) {
  71430. noOptimizationApplied = false;
  71431. allDone = allDone && optimization.apply(scene);
  71432. }
  71433. }
  71434. // If no optimization was applied, this is a failure :(
  71435. if (noOptimizationApplied) {
  71436. if (onFailure) {
  71437. onFailure();
  71438. }
  71439. return;
  71440. }
  71441. // If all optimizations were done, move to next level
  71442. if (allDone) {
  71443. currentPriorityLevel++;
  71444. }
  71445. // Let's the system running for a specific amount of time before checking FPS
  71446. scene.executeWhenReady(function () {
  71447. setTimeout(function () {
  71448. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71449. }, options.trackerDuration);
  71450. });
  71451. };
  71452. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71453. if (!options) {
  71454. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71455. }
  71456. // Let's the system running for a specific amount of time before checking FPS
  71457. scene.executeWhenReady(function () {
  71458. setTimeout(function () {
  71459. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71460. }, options.trackerDuration);
  71461. });
  71462. };
  71463. return SceneOptimizer;
  71464. }());
  71465. BABYLON.SceneOptimizer = SceneOptimizer;
  71466. })(BABYLON || (BABYLON = {}));
  71467. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71468. var BABYLON;
  71469. (function (BABYLON) {
  71470. var OutlineRenderer = /** @class */ (function () {
  71471. function OutlineRenderer(scene) {
  71472. this.zOffset = 1;
  71473. this._scene = scene;
  71474. }
  71475. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71476. var _this = this;
  71477. if (useOverlay === void 0) { useOverlay = false; }
  71478. var scene = this._scene;
  71479. var engine = this._scene.getEngine();
  71480. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71481. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71482. return;
  71483. }
  71484. var mesh = subMesh.getRenderingMesh();
  71485. var material = subMesh.getMaterial();
  71486. if (!material || !scene.activeCamera) {
  71487. return;
  71488. }
  71489. engine.enableEffect(this._effect);
  71490. // Logarithmic depth
  71491. if (material.useLogarithmicDepth) {
  71492. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71493. }
  71494. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71495. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71496. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71497. // Bones
  71498. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71499. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71500. }
  71501. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71502. // Alpha test
  71503. if (material && material.needAlphaTesting()) {
  71504. var alphaTexture = material.getAlphaTestTexture();
  71505. if (alphaTexture) {
  71506. this._effect.setTexture("diffuseSampler", alphaTexture);
  71507. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71508. }
  71509. }
  71510. engine.setZOffset(-this.zOffset);
  71511. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71512. engine.setZOffset(0);
  71513. };
  71514. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71515. var defines = [];
  71516. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71517. var mesh = subMesh.getMesh();
  71518. var material = subMesh.getMaterial();
  71519. if (material) {
  71520. // Alpha test
  71521. if (material.needAlphaTesting()) {
  71522. defines.push("#define ALPHATEST");
  71523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71524. attribs.push(BABYLON.VertexBuffer.UVKind);
  71525. defines.push("#define UV1");
  71526. }
  71527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71529. defines.push("#define UV2");
  71530. }
  71531. }
  71532. //Logarithmic depth
  71533. if (material.useLogarithmicDepth) {
  71534. defines.push("#define LOGARITHMICDEPTH");
  71535. }
  71536. }
  71537. // Bones
  71538. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71541. if (mesh.numBoneInfluencers > 4) {
  71542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71544. }
  71545. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71546. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71547. }
  71548. else {
  71549. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71550. }
  71551. // Instances
  71552. if (useInstances) {
  71553. defines.push("#define INSTANCES");
  71554. attribs.push("world0");
  71555. attribs.push("world1");
  71556. attribs.push("world2");
  71557. attribs.push("world3");
  71558. }
  71559. // Get correct effect
  71560. var join = defines.join("\n");
  71561. if (this._cachedDefines !== join) {
  71562. this._cachedDefines = join;
  71563. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71564. }
  71565. return this._effect.isReady();
  71566. };
  71567. return OutlineRenderer;
  71568. }());
  71569. BABYLON.OutlineRenderer = OutlineRenderer;
  71570. })(BABYLON || (BABYLON = {}));
  71571. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71572. var BABYLON;
  71573. (function (BABYLON) {
  71574. var FaceAdjacencies = /** @class */ (function () {
  71575. function FaceAdjacencies() {
  71576. this.edges = new Array();
  71577. this.edgesConnectedCount = 0;
  71578. }
  71579. return FaceAdjacencies;
  71580. }());
  71581. var EdgesRenderer = /** @class */ (function () {
  71582. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71583. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71584. if (epsilon === void 0) { epsilon = 0.95; }
  71585. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71586. this.edgesWidthScalerForOrthographic = 1000.0;
  71587. this.edgesWidthScalerForPerspective = 50.0;
  71588. this._linesPositions = new Array();
  71589. this._linesNormals = new Array();
  71590. this._linesIndices = new Array();
  71591. this._buffers = {};
  71592. this._checkVerticesInsteadOfIndices = false;
  71593. this._source = source;
  71594. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71595. this._epsilon = epsilon;
  71596. this._prepareRessources();
  71597. this._generateEdgesLines();
  71598. }
  71599. EdgesRenderer.prototype._prepareRessources = function () {
  71600. if (this._lineShader) {
  71601. return;
  71602. }
  71603. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71604. attributes: ["position", "normal"],
  71605. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71606. });
  71607. this._lineShader.disableDepthWrite = true;
  71608. this._lineShader.backFaceCulling = false;
  71609. };
  71610. EdgesRenderer.prototype._rebuild = function () {
  71611. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71612. if (buffer) {
  71613. buffer._rebuild();
  71614. }
  71615. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71616. if (buffer) {
  71617. buffer._rebuild();
  71618. }
  71619. var scene = this._source.getScene();
  71620. var engine = scene.getEngine();
  71621. this._ib = engine.createIndexBuffer(this._linesIndices);
  71622. };
  71623. EdgesRenderer.prototype.dispose = function () {
  71624. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71625. if (buffer) {
  71626. buffer.dispose();
  71627. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71628. }
  71629. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71630. if (buffer) {
  71631. buffer.dispose();
  71632. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71633. }
  71634. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71635. this._lineShader.dispose();
  71636. };
  71637. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71638. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71639. return 0;
  71640. }
  71641. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71642. return 1;
  71643. }
  71644. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71645. return 2;
  71646. }
  71647. return -1;
  71648. };
  71649. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71650. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71651. return 0;
  71652. }
  71653. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71654. return 1;
  71655. }
  71656. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71657. return 2;
  71658. }
  71659. return -1;
  71660. };
  71661. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71662. var needToCreateLine;
  71663. if (edge === undefined) {
  71664. needToCreateLine = true;
  71665. }
  71666. else {
  71667. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71668. needToCreateLine = dotProduct < this._epsilon;
  71669. }
  71670. if (needToCreateLine) {
  71671. var offset = this._linesPositions.length / 3;
  71672. var normal = p0.subtract(p1);
  71673. normal.normalize();
  71674. // Positions
  71675. this._linesPositions.push(p0.x);
  71676. this._linesPositions.push(p0.y);
  71677. this._linesPositions.push(p0.z);
  71678. this._linesPositions.push(p0.x);
  71679. this._linesPositions.push(p0.y);
  71680. this._linesPositions.push(p0.z);
  71681. this._linesPositions.push(p1.x);
  71682. this._linesPositions.push(p1.y);
  71683. this._linesPositions.push(p1.z);
  71684. this._linesPositions.push(p1.x);
  71685. this._linesPositions.push(p1.y);
  71686. this._linesPositions.push(p1.z);
  71687. // Normals
  71688. this._linesNormals.push(p1.x);
  71689. this._linesNormals.push(p1.y);
  71690. this._linesNormals.push(p1.z);
  71691. this._linesNormals.push(-1);
  71692. this._linesNormals.push(p1.x);
  71693. this._linesNormals.push(p1.y);
  71694. this._linesNormals.push(p1.z);
  71695. this._linesNormals.push(1);
  71696. this._linesNormals.push(p0.x);
  71697. this._linesNormals.push(p0.y);
  71698. this._linesNormals.push(p0.z);
  71699. this._linesNormals.push(-1);
  71700. this._linesNormals.push(p0.x);
  71701. this._linesNormals.push(p0.y);
  71702. this._linesNormals.push(p0.z);
  71703. this._linesNormals.push(1);
  71704. // Indices
  71705. this._linesIndices.push(offset);
  71706. this._linesIndices.push(offset + 1);
  71707. this._linesIndices.push(offset + 2);
  71708. this._linesIndices.push(offset);
  71709. this._linesIndices.push(offset + 2);
  71710. this._linesIndices.push(offset + 3);
  71711. }
  71712. };
  71713. EdgesRenderer.prototype._generateEdgesLines = function () {
  71714. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71715. var indices = this._source.getIndices();
  71716. if (!indices || !positions) {
  71717. return;
  71718. }
  71719. // First let's find adjacencies
  71720. var adjacencies = new Array();
  71721. var faceNormals = new Array();
  71722. var index;
  71723. var faceAdjacencies;
  71724. // Prepare faces
  71725. for (index = 0; index < indices.length; index += 3) {
  71726. faceAdjacencies = new FaceAdjacencies();
  71727. var p0Index = indices[index];
  71728. var p1Index = indices[index + 1];
  71729. var p2Index = indices[index + 2];
  71730. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71731. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71732. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71733. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71734. faceNormal.normalize();
  71735. faceNormals.push(faceNormal);
  71736. adjacencies.push(faceAdjacencies);
  71737. }
  71738. // Scan
  71739. for (index = 0; index < adjacencies.length; index++) {
  71740. faceAdjacencies = adjacencies[index];
  71741. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71742. var otherFaceAdjacencies = adjacencies[otherIndex];
  71743. if (faceAdjacencies.edgesConnectedCount === 3) {
  71744. break;
  71745. }
  71746. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71747. continue;
  71748. }
  71749. var otherP0 = indices[otherIndex * 3];
  71750. var otherP1 = indices[otherIndex * 3 + 1];
  71751. var otherP2 = indices[otherIndex * 3 + 2];
  71752. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71753. var otherEdgeIndex = 0;
  71754. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71755. continue;
  71756. }
  71757. switch (edgeIndex) {
  71758. case 0:
  71759. if (this._checkVerticesInsteadOfIndices) {
  71760. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71761. }
  71762. else {
  71763. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71764. }
  71765. break;
  71766. case 1:
  71767. if (this._checkVerticesInsteadOfIndices) {
  71768. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71769. }
  71770. else {
  71771. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71772. }
  71773. break;
  71774. case 2:
  71775. if (this._checkVerticesInsteadOfIndices) {
  71776. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71777. }
  71778. else {
  71779. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71780. }
  71781. break;
  71782. }
  71783. if (otherEdgeIndex === -1) {
  71784. continue;
  71785. }
  71786. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71787. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71788. faceAdjacencies.edgesConnectedCount++;
  71789. otherFaceAdjacencies.edgesConnectedCount++;
  71790. if (faceAdjacencies.edgesConnectedCount === 3) {
  71791. break;
  71792. }
  71793. }
  71794. }
  71795. }
  71796. // Create lines
  71797. for (index = 0; index < adjacencies.length; index++) {
  71798. // 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
  71799. var current = adjacencies[index];
  71800. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71801. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71802. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71803. }
  71804. // Merge into a single mesh
  71805. var engine = this._source.getScene().getEngine();
  71806. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71807. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71808. this._ib = engine.createIndexBuffer(this._linesIndices);
  71809. this._indicesCount = this._linesIndices.length;
  71810. };
  71811. EdgesRenderer.prototype.render = function () {
  71812. var scene = this._source.getScene();
  71813. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71814. return;
  71815. }
  71816. var engine = scene.getEngine();
  71817. this._lineShader._preBind();
  71818. // VBOs
  71819. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71820. scene.resetCachedMaterial();
  71821. this._lineShader.setColor4("color", this._source.edgesColor);
  71822. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71823. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71824. }
  71825. else {
  71826. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71827. }
  71828. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71829. this._lineShader.bind(this._source.getWorldMatrix());
  71830. // Draw order
  71831. engine.draw(true, 0, this._indicesCount);
  71832. this._lineShader.unbind();
  71833. engine.setDepthWrite(true);
  71834. };
  71835. return EdgesRenderer;
  71836. }());
  71837. BABYLON.EdgesRenderer = EdgesRenderer;
  71838. })(BABYLON || (BABYLON = {}));
  71839. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71840. var BABYLON;
  71841. (function (BABYLON) {
  71842. /**
  71843. * Special Glow Blur post process only blurring the alpha channel
  71844. * It enforces keeping the most luminous color in the color channel.
  71845. */
  71846. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71847. __extends(GlowBlurPostProcess, _super);
  71848. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71850. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71851. _this.direction = direction;
  71852. _this.kernel = kernel;
  71853. _this.onApplyObservable.add(function (effect) {
  71854. effect.setFloat2("screenSize", _this.width, _this.height);
  71855. effect.setVector2("direction", _this.direction);
  71856. effect.setFloat("blurWidth", _this.kernel);
  71857. });
  71858. return _this;
  71859. }
  71860. return GlowBlurPostProcess;
  71861. }(BABYLON.PostProcess));
  71862. /**
  71863. * The highlight layer Helps adding a glow effect around a mesh.
  71864. *
  71865. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71866. * glowy meshes to your scene.
  71867. *
  71868. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71869. */
  71870. var HighlightLayer = /** @class */ (function () {
  71871. /**
  71872. * Instantiates a new highlight Layer and references it to the scene..
  71873. * @param name The name of the layer
  71874. * @param scene The scene to use the layer in
  71875. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71876. */
  71877. function HighlightLayer(name, scene, options) {
  71878. this.name = name;
  71879. this._vertexBuffers = {};
  71880. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71881. this._meshes = {};
  71882. this._maxSize = 0;
  71883. this._shouldRender = false;
  71884. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71885. this._excludedMeshes = {};
  71886. /**
  71887. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71888. */
  71889. this.innerGlow = true;
  71890. /**
  71891. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71892. */
  71893. this.outerGlow = true;
  71894. /**
  71895. * Specifies wether the highlight layer is enabled or not.
  71896. */
  71897. this.isEnabled = true;
  71898. /**
  71899. * An event triggered when the highlight layer has been disposed.
  71900. * @type {BABYLON.Observable}
  71901. */
  71902. this.onDisposeObservable = new BABYLON.Observable();
  71903. /**
  71904. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71905. * @type {BABYLON.Observable}
  71906. */
  71907. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71908. /**
  71909. * An event triggered when the highlight layer is being blurred.
  71910. * @type {BABYLON.Observable}
  71911. */
  71912. this.onBeforeBlurObservable = new BABYLON.Observable();
  71913. /**
  71914. * An event triggered when the highlight layer has been blurred.
  71915. * @type {BABYLON.Observable}
  71916. */
  71917. this.onAfterBlurObservable = new BABYLON.Observable();
  71918. /**
  71919. * An event triggered when the glowing blurred texture is being merged in the scene.
  71920. * @type {BABYLON.Observable}
  71921. */
  71922. this.onBeforeComposeObservable = new BABYLON.Observable();
  71923. /**
  71924. * An event triggered when the glowing blurred texture has been merged in the scene.
  71925. * @type {BABYLON.Observable}
  71926. */
  71927. this.onAfterComposeObservable = new BABYLON.Observable();
  71928. /**
  71929. * An event triggered when the highlight layer changes its size.
  71930. * @type {BABYLON.Observable}
  71931. */
  71932. this.onSizeChangedObservable = new BABYLON.Observable();
  71933. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71934. var engine = scene.getEngine();
  71935. this._engine = engine;
  71936. this._maxSize = this._engine.getCaps().maxTextureSize;
  71937. this._scene.highlightLayers.push(this);
  71938. // Warn on stencil.
  71939. if (!this._engine.isStencilEnable) {
  71940. 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 }");
  71941. }
  71942. // Adapt options
  71943. this._options = options || {
  71944. mainTextureRatio: 0.5,
  71945. blurTextureSizeRatio: 0.5,
  71946. blurHorizontalSize: 1.0,
  71947. blurVerticalSize: 1.0,
  71948. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71949. camera: null
  71950. };
  71951. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71952. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71953. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71954. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71955. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71956. // VBO
  71957. var vertices = [];
  71958. vertices.push(1, 1);
  71959. vertices.push(-1, 1);
  71960. vertices.push(-1, -1);
  71961. vertices.push(1, -1);
  71962. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71963. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71964. this._createIndexBuffer();
  71965. // Effect
  71966. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71967. // Render target
  71968. this.setMainTextureSize();
  71969. // Create Textures and post processes
  71970. this.createTextureAndPostProcesses();
  71971. }
  71972. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71973. /**
  71974. * Gets the horizontal size of the blur.
  71975. */
  71976. get: function () {
  71977. return this._horizontalBlurPostprocess.kernel;
  71978. },
  71979. /**
  71980. * Specifies the horizontal size of the blur.
  71981. */
  71982. set: function (value) {
  71983. this._horizontalBlurPostprocess.kernel = value;
  71984. },
  71985. enumerable: true,
  71986. configurable: true
  71987. });
  71988. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71989. /**
  71990. * Gets the vertical size of the blur.
  71991. */
  71992. get: function () {
  71993. return this._verticalBlurPostprocess.kernel;
  71994. },
  71995. /**
  71996. * Specifies the vertical size of the blur.
  71997. */
  71998. set: function (value) {
  71999. this._verticalBlurPostprocess.kernel = value;
  72000. },
  72001. enumerable: true,
  72002. configurable: true
  72003. });
  72004. Object.defineProperty(HighlightLayer.prototype, "camera", {
  72005. /**
  72006. * Gets the camera attached to the layer.
  72007. */
  72008. get: function () {
  72009. return this._options.camera;
  72010. },
  72011. enumerable: true,
  72012. configurable: true
  72013. });
  72014. HighlightLayer.prototype._createIndexBuffer = function () {
  72015. var engine = this._scene.getEngine();
  72016. // Indices
  72017. var indices = [];
  72018. indices.push(0);
  72019. indices.push(1);
  72020. indices.push(2);
  72021. indices.push(0);
  72022. indices.push(2);
  72023. indices.push(3);
  72024. this._indexBuffer = engine.createIndexBuffer(indices);
  72025. };
  72026. HighlightLayer.prototype._rebuild = function () {
  72027. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72028. if (vb) {
  72029. vb._rebuild();
  72030. }
  72031. this._createIndexBuffer();
  72032. };
  72033. /**
  72034. * Creates the render target textures and post processes used in the highlight layer.
  72035. */
  72036. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  72037. var _this = this;
  72038. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  72039. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  72040. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  72041. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  72042. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  72043. width: this._mainTextureDesiredSize.width,
  72044. height: this._mainTextureDesiredSize.height
  72045. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72046. this._mainTexture.activeCamera = this._options.camera;
  72047. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72048. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72049. this._mainTexture.anisotropicFilteringLevel = 1;
  72050. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72051. this._mainTexture.renderParticles = false;
  72052. this._mainTexture.renderList = null;
  72053. this._mainTexture.ignoreCameraViewport = true;
  72054. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  72055. width: blurTextureWidth,
  72056. height: blurTextureHeight
  72057. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72058. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72059. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72060. this._blurTexture.anisotropicFilteringLevel = 16;
  72061. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72062. this._blurTexture.renderParticles = false;
  72063. this._blurTexture.ignoreCameraViewport = true;
  72064. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72065. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  72066. effect.setTexture("textureSampler", _this._mainTexture);
  72067. });
  72068. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  72069. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72070. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72071. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72072. });
  72073. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72074. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72075. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72076. });
  72077. }
  72078. else {
  72079. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72080. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72081. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72082. });
  72083. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72084. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72085. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72086. });
  72087. }
  72088. this._mainTexture.onAfterUnbindObservable.add(function () {
  72089. _this.onBeforeBlurObservable.notifyObservers(_this);
  72090. var internalTexture = _this._blurTexture.getInternalTexture();
  72091. if (internalTexture) {
  72092. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72093. }
  72094. _this.onAfterBlurObservable.notifyObservers(_this);
  72095. });
  72096. // Custom render function
  72097. var renderSubMesh = function (subMesh) {
  72098. if (!_this._meshes) {
  72099. return;
  72100. }
  72101. var material = subMesh.getMaterial();
  72102. var mesh = subMesh.getRenderingMesh();
  72103. var scene = _this._scene;
  72104. var engine = scene.getEngine();
  72105. if (!material) {
  72106. return;
  72107. }
  72108. // Culling
  72109. engine.setState(material.backFaceCulling);
  72110. // Managing instances
  72111. var batch = mesh._getInstancesRenderList(subMesh._id);
  72112. if (batch.mustReturn) {
  72113. return;
  72114. }
  72115. // Excluded Mesh
  72116. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72117. return;
  72118. }
  72119. ;
  72120. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72121. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72122. var emissiveTexture = null;
  72123. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72124. emissiveTexture = material.emissiveTexture;
  72125. }
  72126. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72127. engine.enableEffect(_this._glowMapGenerationEffect);
  72128. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72129. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72130. if (highlightLayerMesh) {
  72131. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72132. }
  72133. else {
  72134. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72135. }
  72136. // Alpha test
  72137. if (material && material.needAlphaTesting()) {
  72138. var alphaTexture = material.getAlphaTestTexture();
  72139. if (alphaTexture) {
  72140. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72141. var textureMatrix = alphaTexture.getTextureMatrix();
  72142. if (textureMatrix) {
  72143. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72144. }
  72145. }
  72146. }
  72147. // Glow emissive only
  72148. if (emissiveTexture) {
  72149. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72150. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72151. }
  72152. // Bones
  72153. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72154. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72155. }
  72156. // Draw
  72157. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72158. }
  72159. else {
  72160. // Need to reset refresh rate of the shadowMap
  72161. _this._mainTexture.resetRefreshCounter();
  72162. }
  72163. };
  72164. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72165. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72166. var index;
  72167. var engine = _this._scene.getEngine();
  72168. if (depthOnlySubMeshes.length) {
  72169. engine.setColorWrite(false);
  72170. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72171. renderSubMesh(depthOnlySubMeshes.data[index]);
  72172. }
  72173. engine.setColorWrite(true);
  72174. }
  72175. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72176. renderSubMesh(opaqueSubMeshes.data[index]);
  72177. }
  72178. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72179. renderSubMesh(alphaTestSubMeshes.data[index]);
  72180. }
  72181. for (index = 0; index < transparentSubMeshes.length; index++) {
  72182. renderSubMesh(transparentSubMeshes.data[index]);
  72183. }
  72184. };
  72185. this._mainTexture.onClearObservable.add(function (engine) {
  72186. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72187. });
  72188. };
  72189. /**
  72190. * Checks for the readiness of the element composing the layer.
  72191. * @param subMesh the mesh to check for
  72192. * @param useInstances specify wether or not to use instances to render the mesh
  72193. * @param emissiveTexture the associated emissive texture used to generate the glow
  72194. * @return true if ready otherwise, false
  72195. */
  72196. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72197. var material = subMesh.getMaterial();
  72198. if (!material) {
  72199. return false;
  72200. }
  72201. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72202. return false;
  72203. }
  72204. var defines = [];
  72205. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72206. var mesh = subMesh.getMesh();
  72207. var uv1 = false;
  72208. var uv2 = false;
  72209. // Alpha test
  72210. if (material && material.needAlphaTesting()) {
  72211. var alphaTexture = material.getAlphaTestTexture();
  72212. if (alphaTexture) {
  72213. defines.push("#define ALPHATEST");
  72214. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72215. alphaTexture.coordinatesIndex === 1) {
  72216. defines.push("#define DIFFUSEUV2");
  72217. uv2 = true;
  72218. }
  72219. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72220. defines.push("#define DIFFUSEUV1");
  72221. uv1 = true;
  72222. }
  72223. }
  72224. }
  72225. // Emissive
  72226. if (emissiveTexture) {
  72227. defines.push("#define EMISSIVE");
  72228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72229. emissiveTexture.coordinatesIndex === 1) {
  72230. defines.push("#define EMISSIVEUV2");
  72231. uv2 = true;
  72232. }
  72233. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72234. defines.push("#define EMISSIVEUV1");
  72235. uv1 = true;
  72236. }
  72237. }
  72238. if (uv1) {
  72239. attribs.push(BABYLON.VertexBuffer.UVKind);
  72240. defines.push("#define UV1");
  72241. }
  72242. if (uv2) {
  72243. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72244. defines.push("#define UV2");
  72245. }
  72246. // Bones
  72247. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72250. if (mesh.numBoneInfluencers > 4) {
  72251. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72252. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72253. }
  72254. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72255. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72256. }
  72257. else {
  72258. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72259. }
  72260. // Instances
  72261. if (useInstances) {
  72262. defines.push("#define INSTANCES");
  72263. attribs.push("world0");
  72264. attribs.push("world1");
  72265. attribs.push("world2");
  72266. attribs.push("world3");
  72267. }
  72268. // Get correct effect
  72269. var join = defines.join("\n");
  72270. if (this._cachedDefines !== join) {
  72271. this._cachedDefines = join;
  72272. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72273. }
  72274. return this._glowMapGenerationEffect.isReady();
  72275. };
  72276. /**
  72277. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72278. */
  72279. HighlightLayer.prototype.render = function () {
  72280. var currentEffect = this._glowMapMergeEffect;
  72281. // Check
  72282. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72283. return;
  72284. var engine = this._scene.getEngine();
  72285. this.onBeforeComposeObservable.notifyObservers(this);
  72286. // Render
  72287. engine.enableEffect(currentEffect);
  72288. engine.setState(false);
  72289. // Cache
  72290. var previousStencilBuffer = engine.getStencilBuffer();
  72291. var previousStencilFunction = engine.getStencilFunction();
  72292. var previousStencilMask = engine.getStencilMask();
  72293. var previousStencilOperationPass = engine.getStencilOperationPass();
  72294. var previousStencilOperationFail = engine.getStencilOperationFail();
  72295. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72296. var previousAlphaMode = engine.getAlphaMode();
  72297. // Texture
  72298. currentEffect.setTexture("textureSampler", this._blurTexture);
  72299. // VBOs
  72300. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72301. // Stencil operations
  72302. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72303. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72304. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72305. // Draw order
  72306. engine.setAlphaMode(this._options.alphaBlendingMode);
  72307. engine.setStencilMask(0x00);
  72308. engine.setStencilBuffer(true);
  72309. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72310. if (this.outerGlow) {
  72311. currentEffect.setFloat("offset", 0);
  72312. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72313. engine.draw(true, 0, 6);
  72314. }
  72315. if (this.innerGlow) {
  72316. currentEffect.setFloat("offset", 1);
  72317. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72318. engine.draw(true, 0, 6);
  72319. }
  72320. // Restore Cache
  72321. engine.setStencilFunction(previousStencilFunction);
  72322. engine.setStencilMask(previousStencilMask);
  72323. engine.setAlphaMode(previousAlphaMode);
  72324. engine.setStencilBuffer(previousStencilBuffer);
  72325. engine.setStencilOperationPass(previousStencilOperationPass);
  72326. engine.setStencilOperationFail(previousStencilOperationFail);
  72327. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72328. engine._stencilState.reset();
  72329. this.onAfterComposeObservable.notifyObservers(this);
  72330. // Handle size changes.
  72331. var size = this._mainTexture.getSize();
  72332. this.setMainTextureSize();
  72333. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72334. // Recreate RTT and post processes on size change.
  72335. this.onSizeChangedObservable.notifyObservers(this);
  72336. this.disposeTextureAndPostProcesses();
  72337. this.createTextureAndPostProcesses();
  72338. }
  72339. };
  72340. /**
  72341. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72342. * @param mesh The mesh to exclude from the highlight layer
  72343. */
  72344. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72345. if (!this._excludedMeshes) {
  72346. return;
  72347. }
  72348. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72349. if (!meshExcluded) {
  72350. this._excludedMeshes[mesh.uniqueId] = {
  72351. mesh: mesh,
  72352. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72353. mesh.getEngine().setStencilBuffer(false);
  72354. }),
  72355. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72356. mesh.getEngine().setStencilBuffer(true);
  72357. }),
  72358. };
  72359. }
  72360. };
  72361. /**
  72362. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72363. * @param mesh The mesh to highlight
  72364. */
  72365. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72366. if (!this._excludedMeshes) {
  72367. return;
  72368. }
  72369. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72370. if (meshExcluded) {
  72371. if (meshExcluded.beforeRender) {
  72372. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72373. }
  72374. if (meshExcluded.afterRender) {
  72375. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72376. }
  72377. }
  72378. this._excludedMeshes[mesh.uniqueId] = null;
  72379. };
  72380. /**
  72381. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72382. * @param mesh The mesh to highlight
  72383. * @param color The color of the highlight
  72384. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72385. */
  72386. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72387. var _this = this;
  72388. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72389. if (!this._meshes) {
  72390. return;
  72391. }
  72392. var meshHighlight = this._meshes[mesh.uniqueId];
  72393. if (meshHighlight) {
  72394. meshHighlight.color = color;
  72395. }
  72396. else {
  72397. this._meshes[mesh.uniqueId] = {
  72398. mesh: mesh,
  72399. color: color,
  72400. // Lambda required for capture due to Observable this context
  72401. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72402. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72403. _this.defaultStencilReference(mesh);
  72404. }
  72405. else {
  72406. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72407. }
  72408. }),
  72409. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72410. glowEmissiveOnly: glowEmissiveOnly
  72411. };
  72412. }
  72413. this._shouldRender = true;
  72414. };
  72415. /**
  72416. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72417. * @param mesh The mesh to highlight
  72418. */
  72419. HighlightLayer.prototype.removeMesh = function (mesh) {
  72420. if (!this._meshes) {
  72421. return;
  72422. }
  72423. var meshHighlight = this._meshes[mesh.uniqueId];
  72424. if (meshHighlight) {
  72425. if (meshHighlight.observerHighlight) {
  72426. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72427. }
  72428. if (meshHighlight.observerDefault) {
  72429. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72430. }
  72431. }
  72432. this._meshes[mesh.uniqueId] = null;
  72433. this._shouldRender = false;
  72434. for (var meshHighlightToCheck in this._meshes) {
  72435. if (meshHighlightToCheck) {
  72436. this._shouldRender = true;
  72437. break;
  72438. }
  72439. }
  72440. };
  72441. /**
  72442. * Returns true if the layer contains information to display, otherwise false.
  72443. */
  72444. HighlightLayer.prototype.shouldRender = function () {
  72445. return this.isEnabled && this._shouldRender;
  72446. };
  72447. /**
  72448. * Sets the main texture desired size which is the closest power of two
  72449. * of the engine canvas size.
  72450. */
  72451. HighlightLayer.prototype.setMainTextureSize = function () {
  72452. if (this._options.mainTextureFixedSize) {
  72453. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72454. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72455. }
  72456. else {
  72457. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72458. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72459. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72460. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72461. }
  72462. };
  72463. /**
  72464. * Force the stencil to the normal expected value for none glowing parts
  72465. */
  72466. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72467. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72468. };
  72469. /**
  72470. * Dispose only the render target textures and post process.
  72471. */
  72472. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72473. this._blurTexture.dispose();
  72474. this._mainTexture.dispose();
  72475. this._downSamplePostprocess.dispose();
  72476. this._horizontalBlurPostprocess.dispose();
  72477. this._verticalBlurPostprocess.dispose();
  72478. };
  72479. /**
  72480. * Dispose the highlight layer and free resources.
  72481. */
  72482. HighlightLayer.prototype.dispose = function () {
  72483. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72484. if (vertexBuffer) {
  72485. vertexBuffer.dispose();
  72486. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72487. }
  72488. if (this._indexBuffer) {
  72489. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72490. this._indexBuffer = null;
  72491. }
  72492. // Clean textures and post processes
  72493. this.disposeTextureAndPostProcesses();
  72494. if (this._meshes) {
  72495. // Clean mesh references
  72496. for (var id in this._meshes) {
  72497. var meshHighlight = this._meshes[id];
  72498. if (meshHighlight && meshHighlight.mesh) {
  72499. if (meshHighlight.observerHighlight) {
  72500. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72501. }
  72502. if (meshHighlight.observerDefault) {
  72503. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72504. }
  72505. }
  72506. }
  72507. this._meshes = null;
  72508. }
  72509. if (this._excludedMeshes) {
  72510. for (var id in this._excludedMeshes) {
  72511. var meshHighlight = this._excludedMeshes[id];
  72512. if (meshHighlight) {
  72513. if (meshHighlight.beforeRender) {
  72514. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72515. }
  72516. if (meshHighlight.afterRender) {
  72517. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72518. }
  72519. }
  72520. }
  72521. this._excludedMeshes = null;
  72522. }
  72523. // Remove from scene
  72524. var index = this._scene.highlightLayers.indexOf(this, 0);
  72525. if (index > -1) {
  72526. this._scene.highlightLayers.splice(index, 1);
  72527. }
  72528. // Callback
  72529. this.onDisposeObservable.notifyObservers(this);
  72530. this.onDisposeObservable.clear();
  72531. this.onBeforeRenderMainTextureObservable.clear();
  72532. this.onBeforeBlurObservable.clear();
  72533. this.onBeforeComposeObservable.clear();
  72534. this.onAfterComposeObservable.clear();
  72535. this.onSizeChangedObservable.clear();
  72536. };
  72537. /**
  72538. * The neutral color used during the preparation of the glow effect.
  72539. * This is black by default as the blend operation is a blend operation.
  72540. */
  72541. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72542. /**
  72543. * Stencil value used for glowing meshes.
  72544. */
  72545. HighlightLayer.glowingMeshStencilReference = 0x02;
  72546. /**
  72547. * Stencil value used for the other meshes in the scene.
  72548. */
  72549. HighlightLayer.normalMeshStencilReference = 0x01;
  72550. return HighlightLayer;
  72551. }());
  72552. BABYLON.HighlightLayer = HighlightLayer;
  72553. })(BABYLON || (BABYLON = {}));
  72554. //# sourceMappingURL=babylon.highlightlayer.js.map
  72555. var BABYLON;
  72556. (function (BABYLON) {
  72557. var AssetTaskState;
  72558. (function (AssetTaskState) {
  72559. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72560. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72561. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72562. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72563. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72564. var AbstractAssetTask = /** @class */ (function () {
  72565. function AbstractAssetTask(name) {
  72566. this.name = name;
  72567. this.isCompleted = false;
  72568. this.taskState = AssetTaskState.INIT;
  72569. }
  72570. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72571. var _this = this;
  72572. this.taskState = AssetTaskState.RUNNING;
  72573. this.runTask(scene, function () {
  72574. _this.onDoneCallback(onSuccess, onError);
  72575. }, function (msg, exception) {
  72576. _this.onErrorCallback(onError, msg, exception);
  72577. });
  72578. };
  72579. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72580. throw new Error("runTask is not implemented");
  72581. };
  72582. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72583. this.taskState = AssetTaskState.ERROR;
  72584. this.errorObject = {
  72585. message: message,
  72586. exception: exception
  72587. };
  72588. if (this.onError) {
  72589. this.onError(this, message, exception);
  72590. }
  72591. onError();
  72592. };
  72593. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72594. try {
  72595. this.taskState = AssetTaskState.DONE;
  72596. this.isCompleted = true;
  72597. if (this.onSuccess) {
  72598. this.onSuccess(this);
  72599. }
  72600. onSuccess();
  72601. }
  72602. catch (e) {
  72603. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72604. }
  72605. };
  72606. return AbstractAssetTask;
  72607. }());
  72608. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72609. var AssetsProgressEvent = /** @class */ (function () {
  72610. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72611. this.remainingCount = remainingCount;
  72612. this.totalCount = totalCount;
  72613. this.task = task;
  72614. }
  72615. return AssetsProgressEvent;
  72616. }());
  72617. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72618. var MeshAssetTask = /** @class */ (function (_super) {
  72619. __extends(MeshAssetTask, _super);
  72620. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72621. var _this = _super.call(this, name) || this;
  72622. _this.name = name;
  72623. _this.meshesNames = meshesNames;
  72624. _this.rootUrl = rootUrl;
  72625. _this.sceneFilename = sceneFilename;
  72626. return _this;
  72627. }
  72628. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72629. var _this = this;
  72630. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72631. _this.loadedMeshes = meshes;
  72632. _this.loadedParticleSystems = particleSystems;
  72633. _this.loadedSkeletons = skeletons;
  72634. onSuccess();
  72635. }, null, function (scene, message, exception) {
  72636. onError(message, exception);
  72637. });
  72638. };
  72639. return MeshAssetTask;
  72640. }(AbstractAssetTask));
  72641. BABYLON.MeshAssetTask = MeshAssetTask;
  72642. var TextFileAssetTask = /** @class */ (function (_super) {
  72643. __extends(TextFileAssetTask, _super);
  72644. function TextFileAssetTask(name, url) {
  72645. var _this = _super.call(this, name) || this;
  72646. _this.name = name;
  72647. _this.url = url;
  72648. return _this;
  72649. }
  72650. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72651. var _this = this;
  72652. BABYLON.Tools.LoadFile(this.url, function (data) {
  72653. _this.text = data;
  72654. onSuccess();
  72655. }, undefined, scene.database, false, function (request, exception) {
  72656. if (request) {
  72657. onError(request.status + " " + request.statusText, exception);
  72658. }
  72659. });
  72660. };
  72661. return TextFileAssetTask;
  72662. }(AbstractAssetTask));
  72663. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72664. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72665. __extends(BinaryFileAssetTask, _super);
  72666. function BinaryFileAssetTask(name, url) {
  72667. var _this = _super.call(this, name) || this;
  72668. _this.name = name;
  72669. _this.url = url;
  72670. return _this;
  72671. }
  72672. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72673. var _this = this;
  72674. BABYLON.Tools.LoadFile(this.url, function (data) {
  72675. _this.data = data;
  72676. onSuccess();
  72677. }, undefined, scene.database, true, function (request, exception) {
  72678. if (request) {
  72679. onError(request.status + " " + request.statusText, exception);
  72680. }
  72681. });
  72682. };
  72683. return BinaryFileAssetTask;
  72684. }(AbstractAssetTask));
  72685. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72686. var ImageAssetTask = /** @class */ (function (_super) {
  72687. __extends(ImageAssetTask, _super);
  72688. function ImageAssetTask(name, url) {
  72689. var _this = _super.call(this, name) || this;
  72690. _this.name = name;
  72691. _this.url = url;
  72692. return _this;
  72693. }
  72694. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72695. var _this = this;
  72696. var img = new Image();
  72697. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72698. img.onload = function () {
  72699. _this.image = img;
  72700. onSuccess();
  72701. };
  72702. img.onerror = function (err) {
  72703. onError("Error loading image", err);
  72704. };
  72705. img.src = this.url;
  72706. };
  72707. return ImageAssetTask;
  72708. }(AbstractAssetTask));
  72709. BABYLON.ImageAssetTask = ImageAssetTask;
  72710. var TextureAssetTask = /** @class */ (function (_super) {
  72711. __extends(TextureAssetTask, _super);
  72712. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72714. var _this = _super.call(this, name) || this;
  72715. _this.name = name;
  72716. _this.url = url;
  72717. _this.noMipmap = noMipmap;
  72718. _this.invertY = invertY;
  72719. _this.samplingMode = samplingMode;
  72720. return _this;
  72721. }
  72722. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72723. var onload = function () {
  72724. onSuccess();
  72725. };
  72726. var onerror = function (msg, exception) {
  72727. onError(msg, exception);
  72728. };
  72729. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72730. };
  72731. return TextureAssetTask;
  72732. }(AbstractAssetTask));
  72733. BABYLON.TextureAssetTask = TextureAssetTask;
  72734. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72735. __extends(CubeTextureAssetTask, _super);
  72736. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72737. var _this = _super.call(this, name) || this;
  72738. _this.name = name;
  72739. _this.url = url;
  72740. _this.extensions = extensions;
  72741. _this.noMipmap = noMipmap;
  72742. _this.files = files;
  72743. return _this;
  72744. }
  72745. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72746. var onload = function () {
  72747. onSuccess();
  72748. };
  72749. var onerror = function (msg, exception) {
  72750. onError(msg, exception);
  72751. };
  72752. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72753. };
  72754. return CubeTextureAssetTask;
  72755. }(AbstractAssetTask));
  72756. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72757. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72758. __extends(HDRCubeTextureAssetTask, _super);
  72759. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72760. if (noMipmap === void 0) { noMipmap = false; }
  72761. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72762. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72763. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72764. var _this = _super.call(this, name) || this;
  72765. _this.name = name;
  72766. _this.url = url;
  72767. _this.size = size;
  72768. _this.noMipmap = noMipmap;
  72769. _this.generateHarmonics = generateHarmonics;
  72770. _this.useInGammaSpace = useInGammaSpace;
  72771. _this.usePMREMGenerator = usePMREMGenerator;
  72772. return _this;
  72773. }
  72774. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72775. var onload = function () {
  72776. onSuccess();
  72777. };
  72778. var onerror = function (message, exception) {
  72779. onError(message, exception);
  72780. };
  72781. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72782. };
  72783. return HDRCubeTextureAssetTask;
  72784. }(AbstractAssetTask));
  72785. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72786. var AssetsManager = /** @class */ (function () {
  72787. function AssetsManager(scene) {
  72788. this.tasks = new Array();
  72789. this.waitingTasksCount = 0;
  72790. //Observables
  72791. this.onTaskSuccessObservable = new BABYLON.Observable();
  72792. this.onTaskErrorObservable = new BABYLON.Observable();
  72793. this.onTasksDoneObservable = new BABYLON.Observable();
  72794. this.onProgressObservable = new BABYLON.Observable();
  72795. this.useDefaultLoadingScreen = true;
  72796. this._scene = scene;
  72797. }
  72798. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72799. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72800. this.tasks.push(task);
  72801. return task;
  72802. };
  72803. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72804. var task = new TextFileAssetTask(taskName, url);
  72805. this.tasks.push(task);
  72806. return task;
  72807. };
  72808. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72809. var task = new BinaryFileAssetTask(taskName, url);
  72810. this.tasks.push(task);
  72811. return task;
  72812. };
  72813. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72814. var task = new ImageAssetTask(taskName, url);
  72815. this.tasks.push(task);
  72816. return task;
  72817. };
  72818. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72819. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72820. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72821. this.tasks.push(task);
  72822. return task;
  72823. };
  72824. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72825. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72826. this.tasks.push(task);
  72827. return task;
  72828. };
  72829. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72830. if (noMipmap === void 0) { noMipmap = false; }
  72831. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72832. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72833. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72834. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72835. this.tasks.push(task);
  72836. return task;
  72837. };
  72838. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72839. this.waitingTasksCount--;
  72840. try {
  72841. if (this.onProgress) {
  72842. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72843. }
  72844. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72845. }
  72846. catch (e) {
  72847. BABYLON.Tools.Error("Error running progress callbacks.");
  72848. console.log(e);
  72849. }
  72850. if (this.waitingTasksCount === 0) {
  72851. try {
  72852. if (this.onFinish) {
  72853. this.onFinish(this.tasks);
  72854. }
  72855. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72856. }
  72857. catch (e) {
  72858. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72859. console.log(e);
  72860. }
  72861. this._scene.getEngine().hideLoadingUI();
  72862. }
  72863. };
  72864. AssetsManager.prototype._runTask = function (task) {
  72865. var _this = this;
  72866. var done = function () {
  72867. try {
  72868. if (_this.onTaskSuccess) {
  72869. _this.onTaskSuccess(task);
  72870. }
  72871. _this.onTaskSuccessObservable.notifyObservers(task);
  72872. _this._decreaseWaitingTasksCount(task);
  72873. }
  72874. catch (e) {
  72875. error("Error executing task success callbacks", e);
  72876. }
  72877. };
  72878. var error = function (message, exception) {
  72879. task.errorObject = task.errorObject || {
  72880. message: message,
  72881. exception: exception
  72882. };
  72883. if (_this.onTaskError) {
  72884. _this.onTaskError(task);
  72885. }
  72886. _this.onTaskErrorObservable.notifyObservers(task);
  72887. _this._decreaseWaitingTasksCount(task);
  72888. };
  72889. task.run(this._scene, done, error);
  72890. };
  72891. AssetsManager.prototype.reset = function () {
  72892. this.tasks = new Array();
  72893. return this;
  72894. };
  72895. AssetsManager.prototype.load = function () {
  72896. this.waitingTasksCount = this.tasks.length;
  72897. if (this.waitingTasksCount === 0) {
  72898. if (this.onFinish) {
  72899. this.onFinish(this.tasks);
  72900. }
  72901. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72902. return this;
  72903. }
  72904. if (this.useDefaultLoadingScreen) {
  72905. this._scene.getEngine().displayLoadingUI();
  72906. }
  72907. for (var index = 0; index < this.tasks.length; index++) {
  72908. var task = this.tasks[index];
  72909. this._runTask(task);
  72910. }
  72911. return this;
  72912. };
  72913. return AssetsManager;
  72914. }());
  72915. BABYLON.AssetsManager = AssetsManager;
  72916. })(BABYLON || (BABYLON = {}));
  72917. //# sourceMappingURL=babylon.assetsManager.js.map
  72918. var BABYLON;
  72919. (function (BABYLON) {
  72920. var serializedGeometries = [];
  72921. var serializeGeometry = function (geometry, serializationGeometries) {
  72922. if (serializedGeometries[geometry.id]) {
  72923. return;
  72924. }
  72925. if (geometry.doNotSerialize) {
  72926. return;
  72927. }
  72928. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72929. serializationGeometries.boxes.push(geometry.serialize());
  72930. }
  72931. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72932. serializationGeometries.spheres.push(geometry.serialize());
  72933. }
  72934. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72935. serializationGeometries.cylinders.push(geometry.serialize());
  72936. }
  72937. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72938. serializationGeometries.toruses.push(geometry.serialize());
  72939. }
  72940. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72941. serializationGeometries.grounds.push(geometry.serialize());
  72942. }
  72943. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72944. serializationGeometries.planes.push(geometry.serialize());
  72945. }
  72946. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72947. serializationGeometries.torusKnots.push(geometry.serialize());
  72948. }
  72949. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72950. throw new Error("Unknown primitive type");
  72951. }
  72952. else {
  72953. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72954. }
  72955. serializedGeometries[geometry.id] = true;
  72956. };
  72957. var serializeMesh = function (mesh, serializationScene) {
  72958. var serializationObject = {};
  72959. // Geometry
  72960. var geometry = mesh._geometry;
  72961. if (geometry) {
  72962. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72963. // 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
  72964. serializeGeometry(geometry, serializationScene.geometries);
  72965. }
  72966. }
  72967. // Custom
  72968. if (mesh.serialize) {
  72969. mesh.serialize(serializationObject);
  72970. }
  72971. return serializationObject;
  72972. };
  72973. var finalizeSingleMesh = function (mesh, serializationObject) {
  72974. //only works if the mesh is already loaded
  72975. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72976. //serialize material
  72977. if (mesh.material) {
  72978. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72979. serializationObject.materials = serializationObject.materials || [];
  72980. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72981. serializationObject.materials.push(mesh.material.serialize());
  72982. }
  72983. }
  72984. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72985. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72986. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72987. serializationObject.multiMaterials.push(mesh.material.serialize());
  72988. }
  72989. }
  72990. }
  72991. //serialize geometry
  72992. var geometry = mesh._geometry;
  72993. if (geometry) {
  72994. if (!serializationObject.geometries) {
  72995. serializationObject.geometries = {};
  72996. serializationObject.geometries.boxes = [];
  72997. serializationObject.geometries.spheres = [];
  72998. serializationObject.geometries.cylinders = [];
  72999. serializationObject.geometries.toruses = [];
  73000. serializationObject.geometries.grounds = [];
  73001. serializationObject.geometries.planes = [];
  73002. serializationObject.geometries.torusKnots = [];
  73003. serializationObject.geometries.vertexData = [];
  73004. }
  73005. serializeGeometry(geometry, serializationObject.geometries);
  73006. }
  73007. // Skeletons
  73008. if (mesh.skeleton) {
  73009. serializationObject.skeletons = serializationObject.skeletons || [];
  73010. serializationObject.skeletons.push(mesh.skeleton.serialize());
  73011. }
  73012. //serialize the actual mesh
  73013. serializationObject.meshes = serializationObject.meshes || [];
  73014. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73015. }
  73016. };
  73017. var SceneSerializer = /** @class */ (function () {
  73018. function SceneSerializer() {
  73019. }
  73020. SceneSerializer.ClearCache = function () {
  73021. serializedGeometries = [];
  73022. };
  73023. SceneSerializer.Serialize = function (scene) {
  73024. var serializationObject = {};
  73025. SceneSerializer.ClearCache();
  73026. // Scene
  73027. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  73028. serializationObject.autoClear = scene.autoClear;
  73029. serializationObject.clearColor = scene.clearColor.asArray();
  73030. serializationObject.ambientColor = scene.ambientColor.asArray();
  73031. serializationObject.gravity = scene.gravity.asArray();
  73032. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  73033. serializationObject.workerCollisions = scene.workerCollisions;
  73034. // Fog
  73035. if (scene.fogMode && scene.fogMode !== 0) {
  73036. serializationObject.fogMode = scene.fogMode;
  73037. serializationObject.fogColor = scene.fogColor.asArray();
  73038. serializationObject.fogStart = scene.fogStart;
  73039. serializationObject.fogEnd = scene.fogEnd;
  73040. serializationObject.fogDensity = scene.fogDensity;
  73041. }
  73042. //Physics
  73043. if (scene.isPhysicsEnabled()) {
  73044. var physicEngine = scene.getPhysicsEngine();
  73045. if (physicEngine) {
  73046. serializationObject.physicsEnabled = true;
  73047. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  73048. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  73049. }
  73050. }
  73051. // Metadata
  73052. if (scene.metadata) {
  73053. serializationObject.metadata = scene.metadata;
  73054. }
  73055. // Morph targets
  73056. serializationObject.morphTargetManagers = [];
  73057. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  73058. var abstractMesh = _a[_i];
  73059. var manager = abstractMesh.morphTargetManager;
  73060. if (manager) {
  73061. serializationObject.morphTargetManagers.push(manager.serialize());
  73062. }
  73063. }
  73064. // Lights
  73065. serializationObject.lights = [];
  73066. var index;
  73067. var light;
  73068. for (index = 0; index < scene.lights.length; index++) {
  73069. light = scene.lights[index];
  73070. if (!light.doNotSerialize) {
  73071. serializationObject.lights.push(light.serialize());
  73072. }
  73073. }
  73074. // Cameras
  73075. serializationObject.cameras = [];
  73076. for (index = 0; index < scene.cameras.length; index++) {
  73077. var camera = scene.cameras[index];
  73078. if (!camera.doNotSerialize) {
  73079. serializationObject.cameras.push(camera.serialize());
  73080. }
  73081. }
  73082. if (scene.activeCamera) {
  73083. serializationObject.activeCameraID = scene.activeCamera.id;
  73084. }
  73085. // Animations
  73086. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73087. // Materials
  73088. serializationObject.materials = [];
  73089. serializationObject.multiMaterials = [];
  73090. var material;
  73091. for (index = 0; index < scene.materials.length; index++) {
  73092. material = scene.materials[index];
  73093. if (!material.doNotSerialize) {
  73094. serializationObject.materials.push(material.serialize());
  73095. }
  73096. }
  73097. // MultiMaterials
  73098. serializationObject.multiMaterials = [];
  73099. for (index = 0; index < scene.multiMaterials.length; index++) {
  73100. var multiMaterial = scene.multiMaterials[index];
  73101. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73102. }
  73103. // Skeletons
  73104. serializationObject.skeletons = [];
  73105. for (index = 0; index < scene.skeletons.length; index++) {
  73106. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73107. }
  73108. // Geometries
  73109. serializationObject.geometries = {};
  73110. serializationObject.geometries.boxes = [];
  73111. serializationObject.geometries.spheres = [];
  73112. serializationObject.geometries.cylinders = [];
  73113. serializationObject.geometries.toruses = [];
  73114. serializationObject.geometries.grounds = [];
  73115. serializationObject.geometries.planes = [];
  73116. serializationObject.geometries.torusKnots = [];
  73117. serializationObject.geometries.vertexData = [];
  73118. serializedGeometries = [];
  73119. var geometries = scene.getGeometries();
  73120. for (index = 0; index < geometries.length; index++) {
  73121. var geometry = geometries[index];
  73122. if (geometry.isReady()) {
  73123. serializeGeometry(geometry, serializationObject.geometries);
  73124. }
  73125. }
  73126. // Meshes
  73127. serializationObject.meshes = [];
  73128. for (index = 0; index < scene.meshes.length; index++) {
  73129. var abstractMesh = scene.meshes[index];
  73130. if (abstractMesh instanceof BABYLON.Mesh) {
  73131. var mesh = abstractMesh;
  73132. if (!mesh.doNotSerialize) {
  73133. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73134. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73135. }
  73136. }
  73137. }
  73138. }
  73139. // Particles Systems
  73140. serializationObject.particleSystems = [];
  73141. for (index = 0; index < scene.particleSystems.length; index++) {
  73142. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73143. }
  73144. // Lens flares
  73145. serializationObject.lensFlareSystems = [];
  73146. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73147. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73148. }
  73149. // Shadows
  73150. serializationObject.shadowGenerators = [];
  73151. for (index = 0; index < scene.lights.length; index++) {
  73152. light = scene.lights[index];
  73153. var shadowGenerator = light.getShadowGenerator();
  73154. if (shadowGenerator) {
  73155. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73156. }
  73157. }
  73158. // Action Manager
  73159. if (scene.actionManager) {
  73160. serializationObject.actions = scene.actionManager.serialize("scene");
  73161. }
  73162. // Audio
  73163. serializationObject.sounds = [];
  73164. for (index = 0; index < scene.soundTracks.length; index++) {
  73165. var soundtrack = scene.soundTracks[index];
  73166. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73167. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73168. }
  73169. }
  73170. return serializationObject;
  73171. };
  73172. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73173. if (withParents === void 0) { withParents = false; }
  73174. if (withChildren === void 0) { withChildren = false; }
  73175. var serializationObject = {};
  73176. SceneSerializer.ClearCache();
  73177. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73178. if (withParents || withChildren) {
  73179. //deliberate for loop! not for each, appended should be processed as well.
  73180. for (var i = 0; i < toSerialize.length; ++i) {
  73181. if (withChildren) {
  73182. toSerialize[i].getDescendants().forEach(function (node) {
  73183. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73184. toSerialize.push(node);
  73185. }
  73186. });
  73187. }
  73188. //make sure the array doesn't contain the object already
  73189. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73190. toSerialize.push(toSerialize[i].parent);
  73191. }
  73192. }
  73193. }
  73194. toSerialize.forEach(function (mesh) {
  73195. finalizeSingleMesh(mesh, serializationObject);
  73196. });
  73197. return serializationObject;
  73198. };
  73199. return SceneSerializer;
  73200. }());
  73201. BABYLON.SceneSerializer = SceneSerializer;
  73202. })(BABYLON || (BABYLON = {}));
  73203. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73204. var BABYLON;
  73205. (function (BABYLON) {
  73206. var ReflectionProbe = /** @class */ (function () {
  73207. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73208. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73209. var _this = this;
  73210. this.name = name;
  73211. this._viewMatrix = BABYLON.Matrix.Identity();
  73212. this._target = BABYLON.Vector3.Zero();
  73213. this._add = BABYLON.Vector3.Zero();
  73214. this.invertYAxis = false;
  73215. this.position = BABYLON.Vector3.Zero();
  73216. this._scene = scene;
  73217. this._scene.reflectionProbes.push(this);
  73218. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73219. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73220. switch (faceIndex) {
  73221. case 0:
  73222. _this._add.copyFromFloats(1, 0, 0);
  73223. break;
  73224. case 1:
  73225. _this._add.copyFromFloats(-1, 0, 0);
  73226. break;
  73227. case 2:
  73228. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73229. break;
  73230. case 3:
  73231. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73232. break;
  73233. case 4:
  73234. _this._add.copyFromFloats(0, 0, 1);
  73235. break;
  73236. case 5:
  73237. _this._add.copyFromFloats(0, 0, -1);
  73238. break;
  73239. }
  73240. if (_this._attachedMesh) {
  73241. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73242. }
  73243. _this.position.addToRef(_this._add, _this._target);
  73244. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73245. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73246. scene._forcedViewPosition = _this.position;
  73247. });
  73248. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73249. scene._forcedViewPosition = null;
  73250. scene.updateTransformMatrix(true);
  73251. });
  73252. if (scene.activeCamera) {
  73253. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73254. }
  73255. }
  73256. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73257. get: function () {
  73258. return this._renderTargetTexture.samples;
  73259. },
  73260. set: function (value) {
  73261. this._renderTargetTexture.samples = value;
  73262. },
  73263. enumerable: true,
  73264. configurable: true
  73265. });
  73266. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73267. get: function () {
  73268. return this._renderTargetTexture.refreshRate;
  73269. },
  73270. set: function (value) {
  73271. this._renderTargetTexture.refreshRate = value;
  73272. },
  73273. enumerable: true,
  73274. configurable: true
  73275. });
  73276. ReflectionProbe.prototype.getScene = function () {
  73277. return this._scene;
  73278. };
  73279. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73280. get: function () {
  73281. return this._renderTargetTexture;
  73282. },
  73283. enumerable: true,
  73284. configurable: true
  73285. });
  73286. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73287. get: function () {
  73288. return this._renderTargetTexture.renderList;
  73289. },
  73290. enumerable: true,
  73291. configurable: true
  73292. });
  73293. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73294. this._attachedMesh = mesh;
  73295. };
  73296. /**
  73297. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73298. *
  73299. * @param renderingGroupId The rendering group id corresponding to its index
  73300. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73301. */
  73302. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73303. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73304. };
  73305. ReflectionProbe.prototype.dispose = function () {
  73306. var index = this._scene.reflectionProbes.indexOf(this);
  73307. if (index !== -1) {
  73308. // Remove from the scene if found
  73309. this._scene.reflectionProbes.splice(index, 1);
  73310. }
  73311. if (this._renderTargetTexture) {
  73312. this._renderTargetTexture.dispose();
  73313. this._renderTargetTexture = null;
  73314. }
  73315. };
  73316. return ReflectionProbe;
  73317. }());
  73318. BABYLON.ReflectionProbe = ReflectionProbe;
  73319. })(BABYLON || (BABYLON = {}));
  73320. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73321. var BABYLON;
  73322. (function (BABYLON) {
  73323. var Layer = /** @class */ (function () {
  73324. function Layer(name, imgUrl, scene, isBackground, color) {
  73325. this.name = name;
  73326. this.scale = new BABYLON.Vector2(1, 1);
  73327. this.offset = new BABYLON.Vector2(0, 0);
  73328. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73329. this.layerMask = 0x0FFFFFFF;
  73330. this._vertexBuffers = {};
  73331. // Events
  73332. /**
  73333. * An event triggered when the layer is disposed.
  73334. * @type {BABYLON.Observable}
  73335. */
  73336. this.onDisposeObservable = new BABYLON.Observable();
  73337. /**
  73338. * An event triggered before rendering the scene
  73339. * @type {BABYLON.Observable}
  73340. */
  73341. this.onBeforeRenderObservable = new BABYLON.Observable();
  73342. /**
  73343. * An event triggered after rendering the scene
  73344. * @type {BABYLON.Observable}
  73345. */
  73346. this.onAfterRenderObservable = new BABYLON.Observable();
  73347. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73348. this.isBackground = isBackground === undefined ? true : isBackground;
  73349. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73350. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73351. this._scene.layers.push(this);
  73352. var engine = this._scene.getEngine();
  73353. // VBO
  73354. var vertices = [];
  73355. vertices.push(1, 1);
  73356. vertices.push(-1, 1);
  73357. vertices.push(-1, -1);
  73358. vertices.push(1, -1);
  73359. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73361. this._createIndexBuffer();
  73362. // Effects
  73363. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73364. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73365. }
  73366. Object.defineProperty(Layer.prototype, "onDispose", {
  73367. set: function (callback) {
  73368. if (this._onDisposeObserver) {
  73369. this.onDisposeObservable.remove(this._onDisposeObserver);
  73370. }
  73371. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73372. },
  73373. enumerable: true,
  73374. configurable: true
  73375. });
  73376. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73377. set: function (callback) {
  73378. if (this._onBeforeRenderObserver) {
  73379. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73380. }
  73381. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73382. },
  73383. enumerable: true,
  73384. configurable: true
  73385. });
  73386. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73387. set: function (callback) {
  73388. if (this._onAfterRenderObserver) {
  73389. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73390. }
  73391. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73392. },
  73393. enumerable: true,
  73394. configurable: true
  73395. });
  73396. Layer.prototype._createIndexBuffer = function () {
  73397. var engine = this._scene.getEngine();
  73398. // Indices
  73399. var indices = [];
  73400. indices.push(0);
  73401. indices.push(1);
  73402. indices.push(2);
  73403. indices.push(0);
  73404. indices.push(2);
  73405. indices.push(3);
  73406. this._indexBuffer = engine.createIndexBuffer(indices);
  73407. };
  73408. Layer.prototype._rebuild = function () {
  73409. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73410. if (vb) {
  73411. vb._rebuild();
  73412. }
  73413. this._createIndexBuffer();
  73414. };
  73415. Layer.prototype.render = function () {
  73416. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73417. // Check
  73418. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73419. return;
  73420. var engine = this._scene.getEngine();
  73421. this.onBeforeRenderObservable.notifyObservers(this);
  73422. // Render
  73423. engine.enableEffect(currentEffect);
  73424. engine.setState(false);
  73425. // Texture
  73426. currentEffect.setTexture("textureSampler", this.texture);
  73427. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73428. // Color
  73429. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73430. // Scale / offset
  73431. currentEffect.setVector2("offset", this.offset);
  73432. currentEffect.setVector2("scale", this.scale);
  73433. // VBOs
  73434. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73435. // Draw order
  73436. if (!this.alphaTest) {
  73437. engine.setAlphaMode(this.alphaBlendingMode);
  73438. engine.draw(true, 0, 6);
  73439. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73440. }
  73441. else {
  73442. engine.draw(true, 0, 6);
  73443. }
  73444. this.onAfterRenderObservable.notifyObservers(this);
  73445. };
  73446. Layer.prototype.dispose = function () {
  73447. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73448. if (vertexBuffer) {
  73449. vertexBuffer.dispose();
  73450. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73451. }
  73452. if (this._indexBuffer) {
  73453. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73454. this._indexBuffer = null;
  73455. }
  73456. if (this.texture) {
  73457. this.texture.dispose();
  73458. this.texture = null;
  73459. }
  73460. // Remove from scene
  73461. var index = this._scene.layers.indexOf(this);
  73462. this._scene.layers.splice(index, 1);
  73463. // Callback
  73464. this.onDisposeObservable.notifyObservers(this);
  73465. this.onDisposeObservable.clear();
  73466. this.onAfterRenderObservable.clear();
  73467. this.onBeforeRenderObservable.clear();
  73468. };
  73469. return Layer;
  73470. }());
  73471. BABYLON.Layer = Layer;
  73472. })(BABYLON || (BABYLON = {}));
  73473. //# sourceMappingURL=babylon.layer.js.map
  73474. var BABYLON;
  73475. (function (BABYLON) {
  73476. var TextureTools = /** @class */ (function () {
  73477. function TextureTools() {
  73478. }
  73479. /**
  73480. * Uses the GPU to create a copy texture rescaled at a given size
  73481. * @param texture Texture to copy from
  73482. * @param width Desired width
  73483. * @param height Desired height
  73484. * @return Generated texture
  73485. */
  73486. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73487. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73488. var scene = texture.getScene();
  73489. var engine = scene.getEngine();
  73490. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73491. rtt.wrapU = texture.wrapU;
  73492. rtt.wrapV = texture.wrapV;
  73493. rtt.uOffset = texture.uOffset;
  73494. rtt.vOffset = texture.vOffset;
  73495. rtt.uScale = texture.uScale;
  73496. rtt.vScale = texture.vScale;
  73497. rtt.uAng = texture.uAng;
  73498. rtt.vAng = texture.vAng;
  73499. rtt.wAng = texture.wAng;
  73500. rtt.coordinatesIndex = texture.coordinatesIndex;
  73501. rtt.level = texture.level;
  73502. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73503. rtt._texture.isReady = false;
  73504. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73505. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73506. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73507. passPostProcess.getEffect().executeWhenCompiled(function () {
  73508. passPostProcess.onApply = function (effect) {
  73509. effect.setTexture("textureSampler", texture);
  73510. };
  73511. var internalTexture = rtt.getInternalTexture();
  73512. if (internalTexture) {
  73513. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73514. engine.unBindFramebuffer(internalTexture);
  73515. rtt.disposeFramebufferObjects();
  73516. passPostProcess.dispose();
  73517. internalTexture.isReady = true;
  73518. }
  73519. });
  73520. return rtt;
  73521. };
  73522. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73523. if (!scene._environmentBRDFTexture) {
  73524. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73525. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73526. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73527. scene._environmentBRDFTexture = texture;
  73528. }
  73529. return scene._environmentBRDFTexture;
  73530. };
  73531. 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=";
  73532. return TextureTools;
  73533. }());
  73534. BABYLON.TextureTools = TextureTools;
  73535. })(BABYLON || (BABYLON = {}));
  73536. //# sourceMappingURL=babylon.textureTools.js.map
  73537. var BABYLON;
  73538. (function (BABYLON) {
  73539. var FramingBehavior = /** @class */ (function () {
  73540. function FramingBehavior() {
  73541. this._mode = FramingBehavior.FitFrustumSidesMode;
  73542. this._radiusScale = 1.0;
  73543. this._positionScale = 0.5;
  73544. this._defaultElevation = 0.3;
  73545. this._elevationReturnTime = 1500;
  73546. this._elevationReturnWaitTime = 1000;
  73547. this._zoomStopsAnimation = false;
  73548. this._framingTime = 1500;
  73549. this._isPointerDown = false;
  73550. this._lastInteractionTime = -Infinity;
  73551. // Framing control
  73552. this._animatables = new Array();
  73553. this._betaIsAnimating = false;
  73554. }
  73555. Object.defineProperty(FramingBehavior.prototype, "name", {
  73556. get: function () {
  73557. return "Framing";
  73558. },
  73559. enumerable: true,
  73560. configurable: true
  73561. });
  73562. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73563. /**
  73564. * Gets current mode used by the behavior.
  73565. */
  73566. get: function () {
  73567. return this._mode;
  73568. },
  73569. /**
  73570. * Sets the current mode used by the behavior
  73571. */
  73572. set: function (mode) {
  73573. this._mode = mode;
  73574. },
  73575. enumerable: true,
  73576. configurable: true
  73577. });
  73578. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73579. /**
  73580. * Gets the scale applied to the radius
  73581. */
  73582. get: function () {
  73583. return this._radiusScale;
  73584. },
  73585. /**
  73586. * Sets the scale applied to the radius (1 by default)
  73587. */
  73588. set: function (radius) {
  73589. this._radiusScale = radius;
  73590. },
  73591. enumerable: true,
  73592. configurable: true
  73593. });
  73594. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73595. /**
  73596. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73597. */
  73598. get: function () {
  73599. return this._positionScale;
  73600. },
  73601. /**
  73602. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73603. */
  73604. set: function (scale) {
  73605. this._positionScale = scale;
  73606. },
  73607. enumerable: true,
  73608. configurable: true
  73609. });
  73610. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73611. /**
  73612. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73613. * behaviour is triggered, in radians.
  73614. */
  73615. get: function () {
  73616. return this._defaultElevation;
  73617. },
  73618. /**
  73619. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73620. * behaviour is triggered, in radians.
  73621. */
  73622. set: function (elevation) {
  73623. this._defaultElevation = elevation;
  73624. },
  73625. enumerable: true,
  73626. configurable: true
  73627. });
  73628. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73629. /**
  73630. * Gets the time (in milliseconds) taken to return to the default beta position.
  73631. * Negative value indicates camera should not return to default.
  73632. */
  73633. get: function () {
  73634. return this._elevationReturnTime;
  73635. },
  73636. /**
  73637. * Sets the time (in milliseconds) taken to return to the default beta position.
  73638. * Negative value indicates camera should not return to default.
  73639. */
  73640. set: function (speed) {
  73641. this._elevationReturnTime = speed;
  73642. },
  73643. enumerable: true,
  73644. configurable: true
  73645. });
  73646. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73647. /**
  73648. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73649. */
  73650. get: function () {
  73651. return this._elevationReturnWaitTime;
  73652. },
  73653. /**
  73654. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73655. */
  73656. set: function (time) {
  73657. this._elevationReturnWaitTime = time;
  73658. },
  73659. enumerable: true,
  73660. configurable: true
  73661. });
  73662. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73663. /**
  73664. * Gets the flag that indicates if user zooming should stop animation.
  73665. */
  73666. get: function () {
  73667. return this._zoomStopsAnimation;
  73668. },
  73669. /**
  73670. * Sets the flag that indicates if user zooming should stop animation.
  73671. */
  73672. set: function (flag) {
  73673. this._zoomStopsAnimation = flag;
  73674. },
  73675. enumerable: true,
  73676. configurable: true
  73677. });
  73678. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73679. /**
  73680. * Gets the transition time when framing the mesh, in milliseconds
  73681. */
  73682. get: function () {
  73683. return this._framingTime;
  73684. },
  73685. /**
  73686. * Sets the transition time when framing the mesh, in milliseconds
  73687. */
  73688. set: function (time) {
  73689. this._framingTime = time;
  73690. },
  73691. enumerable: true,
  73692. configurable: true
  73693. });
  73694. FramingBehavior.prototype.attach = function (camera) {
  73695. var _this = this;
  73696. this._attachedCamera = camera;
  73697. var scene = this._attachedCamera.getScene();
  73698. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73699. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73700. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73701. _this._isPointerDown = true;
  73702. return;
  73703. }
  73704. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73705. _this._isPointerDown = false;
  73706. }
  73707. });
  73708. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73709. if (mesh) {
  73710. _this.zoomOnMesh(mesh);
  73711. }
  73712. });
  73713. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73714. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73715. _this._applyUserInteraction();
  73716. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73717. // back to the default position after a given timeout
  73718. _this._maintainCameraAboveGround();
  73719. });
  73720. };
  73721. FramingBehavior.prototype.detach = function () {
  73722. if (!this._attachedCamera) {
  73723. return;
  73724. }
  73725. var scene = this._attachedCamera.getScene();
  73726. if (this._onPrePointerObservableObserver) {
  73727. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73728. }
  73729. if (this._onAfterCheckInputsObserver) {
  73730. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73731. }
  73732. if (this._onMeshTargetChangedObserver) {
  73733. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73734. }
  73735. this._attachedCamera = null;
  73736. };
  73737. /**
  73738. * Targets the given mesh and updates zoom level accordingly.
  73739. * @param mesh The mesh to target.
  73740. * @param radius Optional. If a cached radius position already exists, overrides default.
  73741. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73742. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73743. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73744. */
  73745. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73746. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73747. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73748. mesh.computeWorldMatrix(true);
  73749. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73750. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73751. };
  73752. /**
  73753. * Targets the given mesh and updates zoom level accordingly.
  73754. * @param mesh The mesh to target.
  73755. * @param radius Optional. If a cached radius position already exists, overrides default.
  73756. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73757. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73758. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73759. */
  73760. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73761. var _this = this;
  73762. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73763. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73764. var zoomTarget;
  73765. if (!this._attachedCamera) {
  73766. return;
  73767. }
  73768. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73769. var bottom = minimumWorld.y;
  73770. var top = maximumWorld.y;
  73771. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73772. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73773. if (focusOnOriginXZ) {
  73774. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73775. }
  73776. else {
  73777. var centerWorld = minimumWorld.add(radiusWorld);
  73778. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73779. }
  73780. if (!this._vectorTransition) {
  73781. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73782. }
  73783. this._betaIsAnimating = true;
  73784. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73785. if (animatable) {
  73786. this._animatables.push(animatable);
  73787. }
  73788. // sets the radius and lower radius bounds
  73789. // Small delta ensures camera is not always at lower zoom limit.
  73790. var radius = 0;
  73791. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73792. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73793. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73794. radius = position;
  73795. }
  73796. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73797. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73798. if (this._attachedCamera.lowerRadiusLimit === null) {
  73799. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73800. }
  73801. }
  73802. // Set sensibilities
  73803. var extend = maximumWorld.subtract(minimumWorld).length();
  73804. this._attachedCamera.panningSensibility = 5000 / extend;
  73805. this._attachedCamera.wheelPrecision = 100 / radius;
  73806. // transition to new radius
  73807. if (!this._radiusTransition) {
  73808. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73809. }
  73810. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73811. if (onAnimationEnd) {
  73812. onAnimationEnd();
  73813. }
  73814. if (_this._attachedCamera) {
  73815. _this._attachedCamera.storeState();
  73816. }
  73817. });
  73818. if (animatable) {
  73819. this._animatables.push(animatable);
  73820. }
  73821. };
  73822. /**
  73823. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73824. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73825. * frustum width.
  73826. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73827. * to fully enclose the mesh in the viewing frustum.
  73828. */
  73829. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73830. var size = maximumWorld.subtract(minimumWorld);
  73831. var boxVectorGlobalDiagonal = size.length();
  73832. var frustumSlope = this._getFrustumSlope();
  73833. // Formula for setting distance
  73834. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73835. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73836. // Horizon distance
  73837. var radius = radiusWithoutFraming * this._radiusScale;
  73838. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73839. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73840. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73841. var camera = this._attachedCamera;
  73842. if (!camera) {
  73843. return 0;
  73844. }
  73845. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73846. // Don't exceed the requested limit
  73847. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73848. }
  73849. // Don't exceed the upper radius limit
  73850. if (camera.upperRadiusLimit) {
  73851. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73852. }
  73853. return distance;
  73854. };
  73855. /**
  73856. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73857. * is automatically returned to its default position (expected to be above ground plane).
  73858. */
  73859. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73860. var _this = this;
  73861. if (this._elevationReturnTime < 0) {
  73862. return;
  73863. }
  73864. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73865. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73866. var limitBeta = Math.PI * 0.5;
  73867. // Bring the camera back up if below the ground plane
  73868. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73869. this._betaIsAnimating = true;
  73870. //Transition to new position
  73871. this.stopAllAnimations();
  73872. if (!this._betaTransition) {
  73873. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73874. }
  73875. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73876. _this._clearAnimationLocks();
  73877. _this.stopAllAnimations();
  73878. });
  73879. if (animatabe) {
  73880. this._animatables.push(animatabe);
  73881. }
  73882. }
  73883. };
  73884. /**
  73885. * Returns the frustum slope based on the canvas ratio and camera FOV
  73886. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73887. */
  73888. FramingBehavior.prototype._getFrustumSlope = function () {
  73889. // Calculate the viewport ratio
  73890. // Aspect Ratio is Height/Width.
  73891. var camera = this._attachedCamera;
  73892. if (!camera) {
  73893. return BABYLON.Vector2.Zero();
  73894. }
  73895. var engine = camera.getScene().getEngine();
  73896. var aspectRatio = engine.getAspectRatio(camera);
  73897. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73898. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73899. var frustumSlopeY = Math.tan(camera.fov / 2);
  73900. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73901. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73902. // along the forward vector.
  73903. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73904. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73905. };
  73906. /**
  73907. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73908. */
  73909. FramingBehavior.prototype._clearAnimationLocks = function () {
  73910. this._betaIsAnimating = false;
  73911. };
  73912. /**
  73913. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73914. */
  73915. FramingBehavior.prototype._applyUserInteraction = function () {
  73916. if (this.isUserIsMoving) {
  73917. this._lastInteractionTime = BABYLON.Tools.Now;
  73918. this.stopAllAnimations();
  73919. this._clearAnimationLocks();
  73920. }
  73921. };
  73922. /**
  73923. * Stops and removes all animations that have been applied to the camera
  73924. */
  73925. FramingBehavior.prototype.stopAllAnimations = function () {
  73926. if (this._attachedCamera) {
  73927. this._attachedCamera.animations = [];
  73928. }
  73929. while (this._animatables.length) {
  73930. if (this._animatables[0]) {
  73931. this._animatables[0].onAnimationEnd = null;
  73932. this._animatables[0].stop();
  73933. }
  73934. this._animatables.shift();
  73935. }
  73936. };
  73937. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73938. /**
  73939. * Gets a value indicating if the user is moving the camera
  73940. */
  73941. get: function () {
  73942. if (!this._attachedCamera) {
  73943. return false;
  73944. }
  73945. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73946. this._attachedCamera.inertialBetaOffset !== 0 ||
  73947. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73948. this._attachedCamera.inertialPanningX !== 0 ||
  73949. this._attachedCamera.inertialPanningY !== 0 ||
  73950. this._isPointerDown;
  73951. },
  73952. enumerable: true,
  73953. configurable: true
  73954. });
  73955. /**
  73956. * The easing function used by animations
  73957. */
  73958. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73959. /**
  73960. * The easing mode used by animations
  73961. */
  73962. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73963. // Statics
  73964. /**
  73965. * The camera can move all the way towards the mesh.
  73966. */
  73967. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73968. /**
  73969. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73970. */
  73971. FramingBehavior.FitFrustumSidesMode = 1;
  73972. return FramingBehavior;
  73973. }());
  73974. BABYLON.FramingBehavior = FramingBehavior;
  73975. })(BABYLON || (BABYLON = {}));
  73976. //# sourceMappingURL=babylon.framingBehavior.js.map
  73977. var BABYLON;
  73978. (function (BABYLON) {
  73979. /**
  73980. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73981. */
  73982. var BouncingBehavior = /** @class */ (function () {
  73983. function BouncingBehavior() {
  73984. /**
  73985. * The duration of the animation, in milliseconds
  73986. */
  73987. this.transitionDuration = 450;
  73988. /**
  73989. * Length of the distance animated by the transition when lower radius is reached
  73990. */
  73991. this.lowerRadiusTransitionRange = 2;
  73992. /**
  73993. * Length of the distance animated by the transition when upper radius is reached
  73994. */
  73995. this.upperRadiusTransitionRange = -2;
  73996. this._autoTransitionRange = false;
  73997. // Animations
  73998. this._radiusIsAnimating = false;
  73999. this._radiusBounceTransition = null;
  74000. this._animatables = new Array();
  74001. }
  74002. Object.defineProperty(BouncingBehavior.prototype, "name", {
  74003. get: function () {
  74004. return "Bouncing";
  74005. },
  74006. enumerable: true,
  74007. configurable: true
  74008. });
  74009. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  74010. /**
  74011. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74012. */
  74013. get: function () {
  74014. return this._autoTransitionRange;
  74015. },
  74016. /**
  74017. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74018. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  74019. */
  74020. set: function (value) {
  74021. var _this = this;
  74022. if (this._autoTransitionRange === value) {
  74023. return;
  74024. }
  74025. this._autoTransitionRange = value;
  74026. var camera = this._attachedCamera;
  74027. if (!camera) {
  74028. return;
  74029. }
  74030. if (value) {
  74031. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74032. if (!mesh) {
  74033. return;
  74034. }
  74035. mesh.computeWorldMatrix(true);
  74036. var diagonal = mesh.getBoundingInfo().diagonalLength;
  74037. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  74038. _this.upperRadiusTransitionRange = diagonal * 0.05;
  74039. });
  74040. }
  74041. else if (this._onMeshTargetChangedObserver) {
  74042. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74043. }
  74044. },
  74045. enumerable: true,
  74046. configurable: true
  74047. });
  74048. BouncingBehavior.prototype.attach = function (camera) {
  74049. var _this = this;
  74050. this._attachedCamera = camera;
  74051. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74052. if (!_this._attachedCamera) {
  74053. return;
  74054. }
  74055. // Add the bounce animation to the lower radius limit
  74056. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  74057. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  74058. }
  74059. // Add the bounce animation to the upper radius limit
  74060. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  74061. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  74062. }
  74063. });
  74064. };
  74065. BouncingBehavior.prototype.detach = function () {
  74066. if (!this._attachedCamera) {
  74067. return;
  74068. }
  74069. if (this._onAfterCheckInputsObserver) {
  74070. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74071. }
  74072. if (this._onMeshTargetChangedObserver) {
  74073. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74074. }
  74075. this._attachedCamera = null;
  74076. };
  74077. /**
  74078. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74079. * @param radiusLimit The limit to check against.
  74080. * @return Bool to indicate if at limit.
  74081. */
  74082. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74083. if (!this._attachedCamera) {
  74084. return false;
  74085. }
  74086. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74087. return true;
  74088. }
  74089. return false;
  74090. };
  74091. /**
  74092. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74093. * @param radiusDelta The delta by which to animate to. Can be negative.
  74094. */
  74095. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74096. var _this = this;
  74097. if (!this._attachedCamera) {
  74098. return;
  74099. }
  74100. if (!this._radiusBounceTransition) {
  74101. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74102. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74103. }
  74104. // Prevent zoom until bounce has completed
  74105. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74106. this._attachedCamera.wheelPrecision = Infinity;
  74107. this._attachedCamera.inertialRadiusOffset = 0;
  74108. // Animate to the radius limit
  74109. this.stopAllAnimations();
  74110. this._radiusIsAnimating = true;
  74111. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74112. if (animatable) {
  74113. this._animatables.push(animatable);
  74114. }
  74115. };
  74116. /**
  74117. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74118. */
  74119. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74120. this._radiusIsAnimating = false;
  74121. if (this._attachedCamera) {
  74122. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74123. }
  74124. };
  74125. /**
  74126. * Stops and removes all animations that have been applied to the camera
  74127. */
  74128. BouncingBehavior.prototype.stopAllAnimations = function () {
  74129. if (this._attachedCamera) {
  74130. this._attachedCamera.animations = [];
  74131. }
  74132. while (this._animatables.length) {
  74133. this._animatables[0].onAnimationEnd = null;
  74134. this._animatables[0].stop();
  74135. this._animatables.shift();
  74136. }
  74137. };
  74138. /**
  74139. * The easing function used by animations
  74140. */
  74141. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74142. /**
  74143. * The easing mode used by animations
  74144. */
  74145. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74146. return BouncingBehavior;
  74147. }());
  74148. BABYLON.BouncingBehavior = BouncingBehavior;
  74149. })(BABYLON || (BABYLON = {}));
  74150. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74151. var BABYLON;
  74152. (function (BABYLON) {
  74153. var AutoRotationBehavior = /** @class */ (function () {
  74154. function AutoRotationBehavior() {
  74155. this._zoomStopsAnimation = false;
  74156. this._idleRotationSpeed = 0.05;
  74157. this._idleRotationWaitTime = 2000;
  74158. this._idleRotationSpinupTime = 2000;
  74159. this._isPointerDown = false;
  74160. this._lastFrameTime = null;
  74161. this._lastInteractionTime = -Infinity;
  74162. this._cameraRotationSpeed = 0;
  74163. this._lastFrameRadius = 0;
  74164. }
  74165. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74166. get: function () {
  74167. return "AutoRotation";
  74168. },
  74169. enumerable: true,
  74170. configurable: true
  74171. });
  74172. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74173. /**
  74174. * Gets the flag that indicates if user zooming should stop animation.
  74175. */
  74176. get: function () {
  74177. return this._zoomStopsAnimation;
  74178. },
  74179. /**
  74180. * Sets the flag that indicates if user zooming should stop animation.
  74181. */
  74182. set: function (flag) {
  74183. this._zoomStopsAnimation = flag;
  74184. },
  74185. enumerable: true,
  74186. configurable: true
  74187. });
  74188. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74189. /**
  74190. * Gets the default speed at which the camera rotates around the model.
  74191. */
  74192. get: function () {
  74193. return this._idleRotationSpeed;
  74194. },
  74195. /**
  74196. * Sets the default speed at which the camera rotates around the model.
  74197. */
  74198. set: function (speed) {
  74199. this._idleRotationSpeed = speed;
  74200. },
  74201. enumerable: true,
  74202. configurable: true
  74203. });
  74204. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74205. /**
  74206. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74207. */
  74208. get: function () {
  74209. return this._idleRotationWaitTime;
  74210. },
  74211. /**
  74212. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74213. */
  74214. set: function (time) {
  74215. this._idleRotationWaitTime = time;
  74216. },
  74217. enumerable: true,
  74218. configurable: true
  74219. });
  74220. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74221. /**
  74222. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74223. */
  74224. get: function () {
  74225. return this._idleRotationSpinupTime;
  74226. },
  74227. /**
  74228. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74229. */
  74230. set: function (time) {
  74231. this._idleRotationSpinupTime = time;
  74232. },
  74233. enumerable: true,
  74234. configurable: true
  74235. });
  74236. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74237. /**
  74238. * Gets a value indicating if the camera is currently rotating because of this behavior
  74239. */
  74240. get: function () {
  74241. return Math.abs(this._cameraRotationSpeed) > 0;
  74242. },
  74243. enumerable: true,
  74244. configurable: true
  74245. });
  74246. AutoRotationBehavior.prototype.attach = function (camera) {
  74247. var _this = this;
  74248. this._attachedCamera = camera;
  74249. var scene = this._attachedCamera.getScene();
  74250. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74251. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74252. _this._isPointerDown = true;
  74253. return;
  74254. }
  74255. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74256. _this._isPointerDown = false;
  74257. }
  74258. });
  74259. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74260. var now = BABYLON.Tools.Now;
  74261. var dt = 0;
  74262. if (_this._lastFrameTime != null) {
  74263. dt = now - _this._lastFrameTime;
  74264. }
  74265. _this._lastFrameTime = now;
  74266. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74267. _this._applyUserInteraction();
  74268. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74269. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74270. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74271. // Step camera rotation by rotation speed
  74272. if (_this._attachedCamera) {
  74273. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74274. }
  74275. });
  74276. };
  74277. AutoRotationBehavior.prototype.detach = function () {
  74278. if (!this._attachedCamera) {
  74279. return;
  74280. }
  74281. var scene = this._attachedCamera.getScene();
  74282. if (this._onPrePointerObservableObserver) {
  74283. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74284. }
  74285. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74286. this._attachedCamera = null;
  74287. };
  74288. /**
  74289. * Returns true if user is scrolling.
  74290. * @return true if user is scrolling.
  74291. */
  74292. AutoRotationBehavior.prototype._userIsZooming = function () {
  74293. if (!this._attachedCamera) {
  74294. return false;
  74295. }
  74296. return this._attachedCamera.inertialRadiusOffset !== 0;
  74297. };
  74298. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74299. if (!this._attachedCamera) {
  74300. return false;
  74301. }
  74302. var zoomHasHitLimit = false;
  74303. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74304. zoomHasHitLimit = true;
  74305. }
  74306. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74307. this._lastFrameRadius = this._attachedCamera.radius;
  74308. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74309. };
  74310. /**
  74311. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74312. */
  74313. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74314. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74315. this._lastInteractionTime = BABYLON.Tools.Now;
  74316. }
  74317. };
  74318. // Tools
  74319. AutoRotationBehavior.prototype._userIsMoving = function () {
  74320. if (!this._attachedCamera) {
  74321. return false;
  74322. }
  74323. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74324. this._attachedCamera.inertialBetaOffset !== 0 ||
  74325. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74326. this._attachedCamera.inertialPanningX !== 0 ||
  74327. this._attachedCamera.inertialPanningY !== 0 ||
  74328. this._isPointerDown;
  74329. };
  74330. return AutoRotationBehavior;
  74331. }());
  74332. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74333. })(BABYLON || (BABYLON = {}));
  74334. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74335. var BABYLON;
  74336. (function (BABYLON) {
  74337. /**
  74338. * This class can be used to get instrumentation data from a Babylon engine
  74339. */
  74340. var EngineInstrumentation = /** @class */ (function () {
  74341. function EngineInstrumentation(engine) {
  74342. this.engine = engine;
  74343. this._captureGPUFrameTime = false;
  74344. this._gpuFrameTime = new BABYLON.PerfCounter();
  74345. this._captureShaderCompilationTime = false;
  74346. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74347. // Observers
  74348. this._onBeginFrameObserver = null;
  74349. this._onEndFrameObserver = null;
  74350. this._onBeforeShaderCompilationObserver = null;
  74351. this._onAfterShaderCompilationObserver = null;
  74352. }
  74353. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74354. // Properties
  74355. /**
  74356. * Gets the perf counter used for GPU frame time
  74357. */
  74358. get: function () {
  74359. return this._gpuFrameTime;
  74360. },
  74361. enumerable: true,
  74362. configurable: true
  74363. });
  74364. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74365. /**
  74366. * Gets the GPU frame time capture status
  74367. */
  74368. get: function () {
  74369. return this._captureGPUFrameTime;
  74370. },
  74371. /**
  74372. * Enable or disable the GPU frame time capture
  74373. */
  74374. set: function (value) {
  74375. var _this = this;
  74376. if (value === this._captureGPUFrameTime) {
  74377. return;
  74378. }
  74379. this._captureGPUFrameTime = value;
  74380. if (value) {
  74381. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74382. if (!_this._gpuFrameTimeToken) {
  74383. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74384. }
  74385. });
  74386. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74387. if (!_this._gpuFrameTimeToken) {
  74388. return;
  74389. }
  74390. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74391. if (time > -1) {
  74392. _this._gpuFrameTimeToken = null;
  74393. _this._gpuFrameTime.fetchNewFrame();
  74394. _this._gpuFrameTime.addCount(time, true);
  74395. }
  74396. });
  74397. }
  74398. else {
  74399. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74400. this._onBeginFrameObserver = null;
  74401. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74402. this._onEndFrameObserver = null;
  74403. }
  74404. },
  74405. enumerable: true,
  74406. configurable: true
  74407. });
  74408. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74409. /**
  74410. * Gets the perf counter used for shader compilation time
  74411. */
  74412. get: function () {
  74413. return this._shaderCompilationTime;
  74414. },
  74415. enumerable: true,
  74416. configurable: true
  74417. });
  74418. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74419. /**
  74420. * Gets the shader compilation time capture status
  74421. */
  74422. get: function () {
  74423. return this._captureShaderCompilationTime;
  74424. },
  74425. /**
  74426. * Enable or disable the shader compilation time capture
  74427. */
  74428. set: function (value) {
  74429. var _this = this;
  74430. if (value === this._captureShaderCompilationTime) {
  74431. return;
  74432. }
  74433. this._captureShaderCompilationTime = value;
  74434. if (value) {
  74435. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74436. _this._shaderCompilationTime.fetchNewFrame();
  74437. _this._shaderCompilationTime.beginMonitoring();
  74438. });
  74439. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74440. _this._shaderCompilationTime.endMonitoring();
  74441. });
  74442. }
  74443. else {
  74444. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74445. this._onBeforeShaderCompilationObserver = null;
  74446. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74447. this._onAfterShaderCompilationObserver = null;
  74448. }
  74449. },
  74450. enumerable: true,
  74451. configurable: true
  74452. });
  74453. EngineInstrumentation.prototype.dispose = function () {
  74454. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74455. this._onBeginFrameObserver = null;
  74456. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74457. this._onEndFrameObserver = null;
  74458. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74459. this._onBeforeShaderCompilationObserver = null;
  74460. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74461. this._onAfterShaderCompilationObserver = null;
  74462. this.engine = null;
  74463. };
  74464. return EngineInstrumentation;
  74465. }());
  74466. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74467. })(BABYLON || (BABYLON = {}));
  74468. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74469. var BABYLON;
  74470. (function (BABYLON) {
  74471. /**
  74472. * This class can be used to get instrumentation data from a Babylon engine
  74473. */
  74474. var SceneInstrumentation = /** @class */ (function () {
  74475. function SceneInstrumentation(scene) {
  74476. var _this = this;
  74477. this.scene = scene;
  74478. this._captureActiveMeshesEvaluationTime = false;
  74479. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74480. this._captureRenderTargetsRenderTime = false;
  74481. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74482. this._captureFrameTime = false;
  74483. this._frameTime = new BABYLON.PerfCounter();
  74484. this._captureRenderTime = false;
  74485. this._renderTime = new BABYLON.PerfCounter();
  74486. this._captureInterFrameTime = false;
  74487. this._interFrameTime = new BABYLON.PerfCounter();
  74488. this._captureParticlesRenderTime = false;
  74489. this._particlesRenderTime = new BABYLON.PerfCounter();
  74490. this._captureSpritesRenderTime = false;
  74491. this._spritesRenderTime = new BABYLON.PerfCounter();
  74492. this._capturePhysicsTime = false;
  74493. this._physicsTime = new BABYLON.PerfCounter();
  74494. this._captureAnimationsTime = false;
  74495. this._animationsTime = new BABYLON.PerfCounter();
  74496. // Observers
  74497. this._onBeforeActiveMeshesEvaluationObserver = null;
  74498. this._onAfterActiveMeshesEvaluationObserver = null;
  74499. this._onBeforeRenderTargetsRenderObserver = null;
  74500. this._onAfterRenderTargetsRenderObserver = null;
  74501. this._onAfterRenderObserver = null;
  74502. this._onBeforeDrawPhaseObserver = null;
  74503. this._onAfterDrawPhaseObserver = null;
  74504. this._onBeforeAnimationsObserver = null;
  74505. this._onBeforeParticlesRenderingObserver = null;
  74506. this._onAfterParticlesRenderingObserver = null;
  74507. this._onBeforeSpritesRenderingObserver = null;
  74508. this._onAfterSpritesRenderingObserver = null;
  74509. this._onBeforePhysicsObserver = null;
  74510. this._onAfterPhysicsObserver = null;
  74511. this._onAfterAnimationsObserver = null;
  74512. // Before render
  74513. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  74514. if (_this._captureActiveMeshesEvaluationTime) {
  74515. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74516. }
  74517. if (_this._captureRenderTargetsRenderTime) {
  74518. _this._renderTargetsRenderTime.fetchNewFrame();
  74519. }
  74520. if (_this._captureFrameTime) {
  74521. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74522. _this._frameTime.beginMonitoring();
  74523. }
  74524. if (_this._captureInterFrameTime) {
  74525. _this._interFrameTime.endMonitoring();
  74526. }
  74527. if (_this._captureParticlesRenderTime) {
  74528. _this._particlesRenderTime.fetchNewFrame();
  74529. }
  74530. if (_this._captureSpritesRenderTime) {
  74531. _this._spritesRenderTime.fetchNewFrame();
  74532. }
  74533. if (_this._captureAnimationsTime) {
  74534. _this._animationsTime.beginMonitoring();
  74535. }
  74536. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  74537. });
  74538. // After render
  74539. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74540. if (_this._captureFrameTime) {
  74541. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74542. _this._frameTime.endMonitoring();
  74543. }
  74544. if (_this._captureRenderTime) {
  74545. _this._renderTime.endMonitoring(false);
  74546. }
  74547. if (_this._captureInterFrameTime) {
  74548. _this._interFrameTime.beginMonitoring();
  74549. }
  74550. });
  74551. }
  74552. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  74553. // Properties
  74554. /**
  74555. * Gets the perf counter used for active meshes evaluation time
  74556. */
  74557. get: function () {
  74558. return this._activeMeshesEvaluationTime;
  74559. },
  74560. enumerable: true,
  74561. configurable: true
  74562. });
  74563. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74564. /**
  74565. * Gets the active meshes evaluation time capture status
  74566. */
  74567. get: function () {
  74568. return this._captureActiveMeshesEvaluationTime;
  74569. },
  74570. /**
  74571. * Enable or disable the active meshes evaluation time capture
  74572. */
  74573. set: function (value) {
  74574. var _this = this;
  74575. if (value === this._captureActiveMeshesEvaluationTime) {
  74576. return;
  74577. }
  74578. this._captureActiveMeshesEvaluationTime = value;
  74579. if (value) {
  74580. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74581. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74582. _this._activeMeshesEvaluationTime.beginMonitoring();
  74583. });
  74584. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74585. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74586. _this._activeMeshesEvaluationTime.endMonitoring();
  74587. });
  74588. }
  74589. else {
  74590. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74591. this._onBeforeActiveMeshesEvaluationObserver = null;
  74592. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74593. this._onAfterActiveMeshesEvaluationObserver = null;
  74594. }
  74595. },
  74596. enumerable: true,
  74597. configurable: true
  74598. });
  74599. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74600. /**
  74601. * Gets the perf counter used for render targets render time
  74602. */
  74603. get: function () {
  74604. return this._renderTargetsRenderTime;
  74605. },
  74606. enumerable: true,
  74607. configurable: true
  74608. });
  74609. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74610. /**
  74611. * Gets the render targets render time capture status
  74612. */
  74613. get: function () {
  74614. return this._captureRenderTargetsRenderTime;
  74615. },
  74616. /**
  74617. * Enable or disable the render targets render time capture
  74618. */
  74619. set: function (value) {
  74620. var _this = this;
  74621. if (value === this._captureRenderTargetsRenderTime) {
  74622. return;
  74623. }
  74624. this._captureRenderTargetsRenderTime = value;
  74625. if (value) {
  74626. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74627. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74628. _this._renderTargetsRenderTime.beginMonitoring();
  74629. });
  74630. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74631. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74632. _this._renderTargetsRenderTime.endMonitoring(false);
  74633. });
  74634. }
  74635. else {
  74636. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74637. this._onBeforeRenderTargetsRenderObserver = null;
  74638. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74639. this._onAfterRenderTargetsRenderObserver = null;
  74640. }
  74641. },
  74642. enumerable: true,
  74643. configurable: true
  74644. });
  74645. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  74646. /**
  74647. * Gets the perf counter used for particles render time
  74648. */
  74649. get: function () {
  74650. return this._particlesRenderTime;
  74651. },
  74652. enumerable: true,
  74653. configurable: true
  74654. });
  74655. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  74656. /**
  74657. * Gets the particles render time capture status
  74658. */
  74659. get: function () {
  74660. return this._captureParticlesRenderTime;
  74661. },
  74662. /**
  74663. * Enable or disable the particles render time capture
  74664. */
  74665. set: function (value) {
  74666. var _this = this;
  74667. if (value === this._captureParticlesRenderTime) {
  74668. return;
  74669. }
  74670. this._captureParticlesRenderTime = value;
  74671. if (value) {
  74672. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  74673. BABYLON.Tools.StartPerformanceCounter("Particles");
  74674. _this._particlesRenderTime.beginMonitoring();
  74675. });
  74676. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  74677. BABYLON.Tools.EndPerformanceCounter("Particles");
  74678. _this._particlesRenderTime.endMonitoring(false);
  74679. });
  74680. }
  74681. else {
  74682. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74683. this._onBeforeParticlesRenderingObserver = null;
  74684. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74685. this._onAfterParticlesRenderingObserver = null;
  74686. }
  74687. },
  74688. enumerable: true,
  74689. configurable: true
  74690. });
  74691. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  74692. /**
  74693. * Gets the perf counter used for sprites render time
  74694. */
  74695. get: function () {
  74696. return this._spritesRenderTime;
  74697. },
  74698. enumerable: true,
  74699. configurable: true
  74700. });
  74701. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  74702. /**
  74703. * Gets the sprites render time capture status
  74704. */
  74705. get: function () {
  74706. return this._captureSpritesRenderTime;
  74707. },
  74708. /**
  74709. * Enable or disable the sprites render time capture
  74710. */
  74711. set: function (value) {
  74712. var _this = this;
  74713. if (value === this._captureSpritesRenderTime) {
  74714. return;
  74715. }
  74716. this._captureSpritesRenderTime = value;
  74717. if (value) {
  74718. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  74719. BABYLON.Tools.StartPerformanceCounter("Sprites");
  74720. _this._spritesRenderTime.beginMonitoring();
  74721. });
  74722. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  74723. BABYLON.Tools.EndPerformanceCounter("Sprites");
  74724. _this._spritesRenderTime.endMonitoring(false);
  74725. });
  74726. }
  74727. else {
  74728. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74729. this._onBeforeSpritesRenderingObserver = null;
  74730. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74731. this._onAfterSpritesRenderingObserver = null;
  74732. }
  74733. },
  74734. enumerable: true,
  74735. configurable: true
  74736. });
  74737. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  74738. /**
  74739. * Gets the perf counter used for physics time
  74740. */
  74741. get: function () {
  74742. return this._physicsTime;
  74743. },
  74744. enumerable: true,
  74745. configurable: true
  74746. });
  74747. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  74748. /**
  74749. * Gets the physics time capture status
  74750. */
  74751. get: function () {
  74752. return this._capturePhysicsTime;
  74753. },
  74754. /**
  74755. * Enable or disable the physics time capture
  74756. */
  74757. set: function (value) {
  74758. var _this = this;
  74759. if (value === this._capturePhysicsTime) {
  74760. return;
  74761. }
  74762. this._capturePhysicsTime = value;
  74763. if (value) {
  74764. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  74765. BABYLON.Tools.StartPerformanceCounter("Physics");
  74766. _this._physicsTime.beginMonitoring();
  74767. });
  74768. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  74769. BABYLON.Tools.EndPerformanceCounter("Physics");
  74770. _this._physicsTime.endMonitoring();
  74771. });
  74772. }
  74773. else {
  74774. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74775. this._onBeforePhysicsObserver = null;
  74776. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74777. this._onAfterPhysicsObserver = null;
  74778. }
  74779. },
  74780. enumerable: true,
  74781. configurable: true
  74782. });
  74783. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  74784. /**
  74785. * Gets the perf counter used for animations time
  74786. */
  74787. get: function () {
  74788. return this._animationsTime;
  74789. },
  74790. enumerable: true,
  74791. configurable: true
  74792. });
  74793. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  74794. /**
  74795. * Gets the animations time capture status
  74796. */
  74797. get: function () {
  74798. return this._captureAnimationsTime;
  74799. },
  74800. /**
  74801. * Enable or disable the animations time capture
  74802. */
  74803. set: function (value) {
  74804. var _this = this;
  74805. if (value === this._captureAnimationsTime) {
  74806. return;
  74807. }
  74808. this._captureAnimationsTime = value;
  74809. if (value) {
  74810. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  74811. _this._animationsTime.endMonitoring();
  74812. });
  74813. }
  74814. else {
  74815. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74816. this._onAfterAnimationsObserver = null;
  74817. }
  74818. },
  74819. enumerable: true,
  74820. configurable: true
  74821. });
  74822. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74823. /**
  74824. * Gets the perf counter used for frame time capture
  74825. */
  74826. get: function () {
  74827. return this._frameTime;
  74828. },
  74829. enumerable: true,
  74830. configurable: true
  74831. });
  74832. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74833. /**
  74834. * Gets the frame time capture status
  74835. */
  74836. get: function () {
  74837. return this._captureFrameTime;
  74838. },
  74839. /**
  74840. * Enable or disable the frame time capture
  74841. */
  74842. set: function (value) {
  74843. this._captureFrameTime = value;
  74844. },
  74845. enumerable: true,
  74846. configurable: true
  74847. });
  74848. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  74849. /**
  74850. * Gets the perf counter used for inter-frames time capture
  74851. */
  74852. get: function () {
  74853. return this._interFrameTime;
  74854. },
  74855. enumerable: true,
  74856. configurable: true
  74857. });
  74858. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  74859. /**
  74860. * Gets the inter-frames time capture status
  74861. */
  74862. get: function () {
  74863. return this._captureInterFrameTime;
  74864. },
  74865. /**
  74866. * Enable or disable the inter-frames time capture
  74867. */
  74868. set: function (value) {
  74869. this._captureInterFrameTime = value;
  74870. },
  74871. enumerable: true,
  74872. configurable: true
  74873. });
  74874. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  74875. /**
  74876. * Gets the perf counter used for render time capture
  74877. */
  74878. get: function () {
  74879. return this._renderTime;
  74880. },
  74881. enumerable: true,
  74882. configurable: true
  74883. });
  74884. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  74885. /**
  74886. * Gets the render time capture status
  74887. */
  74888. get: function () {
  74889. return this._captureRenderTime;
  74890. },
  74891. /**
  74892. * Enable or disable the render time capture
  74893. */
  74894. set: function (value) {
  74895. var _this = this;
  74896. if (value === this._captureRenderTime) {
  74897. return;
  74898. }
  74899. this._captureRenderTime = value;
  74900. if (value) {
  74901. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  74902. _this._renderTime.beginMonitoring();
  74903. BABYLON.Tools.StartPerformanceCounter("Main render");
  74904. });
  74905. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  74906. _this._renderTime.endMonitoring(false);
  74907. BABYLON.Tools.EndPerformanceCounter("Main render");
  74908. });
  74909. }
  74910. else {
  74911. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74912. this._onBeforeDrawPhaseObserver = null;
  74913. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74914. this._onAfterDrawPhaseObserver = null;
  74915. }
  74916. },
  74917. enumerable: true,
  74918. configurable: true
  74919. });
  74920. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  74921. /**
  74922. * Gets the perf counter used for frame time capture
  74923. */
  74924. get: function () {
  74925. return this.scene.getEngine()._drawCalls;
  74926. },
  74927. enumerable: true,
  74928. configurable: true
  74929. });
  74930. SceneInstrumentation.prototype.dispose = function () {
  74931. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74932. this._onAfterRenderObserver = null;
  74933. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74934. this._onBeforeActiveMeshesEvaluationObserver = null;
  74935. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74936. this._onAfterActiveMeshesEvaluationObserver = null;
  74937. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74938. this._onBeforeRenderTargetsRenderObserver = null;
  74939. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74940. this._onAfterRenderTargetsRenderObserver = null;
  74941. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  74942. this._onBeforeAnimationsObserver = null;
  74943. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74944. this._onBeforeParticlesRenderingObserver = null;
  74945. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74946. this._onAfterParticlesRenderingObserver = null;
  74947. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74948. this._onBeforeSpritesRenderingObserver = null;
  74949. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74950. this._onAfterSpritesRenderingObserver = null;
  74951. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74952. this._onBeforeDrawPhaseObserver = null;
  74953. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74954. this._onAfterDrawPhaseObserver = null;
  74955. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74956. this._onBeforePhysicsObserver = null;
  74957. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74958. this._onAfterPhysicsObserver = null;
  74959. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74960. this._onAfterAnimationsObserver = null;
  74961. this.scene = null;
  74962. };
  74963. return SceneInstrumentation;
  74964. }());
  74965. BABYLON.SceneInstrumentation = SceneInstrumentation;
  74966. })(BABYLON || (BABYLON = {}));
  74967. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  74968. var BABYLON;
  74969. (function (BABYLON) {
  74970. var _TimeToken = /** @class */ (function () {
  74971. function _TimeToken() {
  74972. this._timeElapsedQueryEnded = false;
  74973. }
  74974. return _TimeToken;
  74975. }());
  74976. BABYLON._TimeToken = _TimeToken;
  74977. })(BABYLON || (BABYLON = {}));
  74978. //# sourceMappingURL=babylon.timeToken.js.map
  74979. 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}"};
  74980. 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};"};
  74981. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74982. var BABYLON;
  74983. (function (BABYLON) {
  74984. var GridMaterialDefines = /** @class */ (function (_super) {
  74985. __extends(GridMaterialDefines, _super);
  74986. function GridMaterialDefines() {
  74987. var _this = _super.call(this) || this;
  74988. _this.TRANSPARENT = false;
  74989. _this.FOG = false;
  74990. _this.PREMULTIPLYALPHA = false;
  74991. _this.rebuild();
  74992. return _this;
  74993. }
  74994. return GridMaterialDefines;
  74995. }(BABYLON.MaterialDefines));
  74996. /**
  74997. * The grid materials allows you to wrap any shape with a grid.
  74998. * Colors are customizable.
  74999. */
  75000. var GridMaterial = /** @class */ (function (_super) {
  75001. __extends(GridMaterial, _super);
  75002. /**
  75003. * constructor
  75004. * @param name The name given to the material in order to identify it afterwards.
  75005. * @param scene The scene the material is used in.
  75006. */
  75007. function GridMaterial(name, scene) {
  75008. var _this = _super.call(this, name, scene) || this;
  75009. /**
  75010. * Main color of the grid (e.g. between lines)
  75011. */
  75012. _this.mainColor = BABYLON.Color3.Black();
  75013. /**
  75014. * Color of the grid lines.
  75015. */
  75016. _this.lineColor = BABYLON.Color3.Teal();
  75017. /**
  75018. * The scale of the grid compared to unit.
  75019. */
  75020. _this.gridRatio = 1.0;
  75021. /**
  75022. * Allows setting an offset for the grid lines.
  75023. */
  75024. _this.gridOffset = BABYLON.Vector3.Zero();
  75025. /**
  75026. * The frequency of thicker lines.
  75027. */
  75028. _this.majorUnitFrequency = 10;
  75029. /**
  75030. * The visibility of minor units in the grid.
  75031. */
  75032. _this.minorUnitVisibility = 0.33;
  75033. /**
  75034. * The grid opacity outside of the lines.
  75035. */
  75036. _this.opacity = 1.0;
  75037. /**
  75038. * Determine RBG output is premultiplied by alpha value.
  75039. */
  75040. _this.preMultiplyAlpha = false;
  75041. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  75042. return _this;
  75043. }
  75044. /**
  75045. * Returns wehter or not the grid requires alpha blending.
  75046. */
  75047. GridMaterial.prototype.needAlphaBlending = function () {
  75048. return this.opacity < 1.0;
  75049. };
  75050. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75051. if (this.isFrozen) {
  75052. if (this._wasPreviouslyReady && subMesh.effect) {
  75053. return true;
  75054. }
  75055. }
  75056. if (!subMesh._materialDefines) {
  75057. subMesh._materialDefines = new GridMaterialDefines();
  75058. }
  75059. var defines = subMesh._materialDefines;
  75060. var scene = this.getScene();
  75061. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75062. if (this._renderId === scene.getRenderId()) {
  75063. return true;
  75064. }
  75065. }
  75066. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  75067. defines.TRANSPARENT = !defines.TRANSPARENT;
  75068. defines.markAsUnprocessed();
  75069. }
  75070. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  75071. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  75072. defines.markAsUnprocessed();
  75073. }
  75074. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  75075. // Get correct effect
  75076. if (defines.isDirty) {
  75077. defines.markAsProcessed();
  75078. scene.resetCachedMaterial();
  75079. // Attributes
  75080. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75081. // Defines
  75082. var join = defines.toString();
  75083. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  75084. }
  75085. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75086. return false;
  75087. }
  75088. this._renderId = scene.getRenderId();
  75089. this._wasPreviouslyReady = true;
  75090. return true;
  75091. };
  75092. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75093. var scene = this.getScene();
  75094. var defines = subMesh._materialDefines;
  75095. if (!defines) {
  75096. return;
  75097. }
  75098. var effect = subMesh.effect;
  75099. if (!effect) {
  75100. return;
  75101. }
  75102. this._activeEffect = effect;
  75103. // Matrices
  75104. this.bindOnlyWorldMatrix(world);
  75105. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  75106. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  75107. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  75108. // Uniforms
  75109. if (this._mustRebind(scene, effect)) {
  75110. this._activeEffect.setColor3("mainColor", this.mainColor);
  75111. this._activeEffect.setColor3("lineColor", this.lineColor);
  75112. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  75113. this._gridControl.x = this.gridRatio;
  75114. this._gridControl.y = Math.round(this.majorUnitFrequency);
  75115. this._gridControl.z = this.minorUnitVisibility;
  75116. this._gridControl.w = this.opacity;
  75117. this._activeEffect.setVector4("gridControl", this._gridControl);
  75118. }
  75119. // Fog
  75120. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75121. this._afterBind(mesh, this._activeEffect);
  75122. };
  75123. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  75124. _super.prototype.dispose.call(this, forceDisposeEffect);
  75125. };
  75126. GridMaterial.prototype.clone = function (name) {
  75127. var _this = this;
  75128. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  75129. };
  75130. GridMaterial.prototype.serialize = function () {
  75131. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75132. serializationObject.customType = "BABYLON.GridMaterial";
  75133. return serializationObject;
  75134. };
  75135. GridMaterial.prototype.getClassName = function () {
  75136. return "GridMaterial";
  75137. };
  75138. GridMaterial.Parse = function (source, scene, rootUrl) {
  75139. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  75140. };
  75141. __decorate([
  75142. BABYLON.serializeAsColor3()
  75143. ], GridMaterial.prototype, "mainColor", void 0);
  75144. __decorate([
  75145. BABYLON.serializeAsColor3()
  75146. ], GridMaterial.prototype, "lineColor", void 0);
  75147. __decorate([
  75148. BABYLON.serialize()
  75149. ], GridMaterial.prototype, "gridRatio", void 0);
  75150. __decorate([
  75151. BABYLON.serializeAsColor3()
  75152. ], GridMaterial.prototype, "gridOffset", void 0);
  75153. __decorate([
  75154. BABYLON.serialize()
  75155. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  75156. __decorate([
  75157. BABYLON.serialize()
  75158. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  75159. __decorate([
  75160. BABYLON.serialize()
  75161. ], GridMaterial.prototype, "opacity", void 0);
  75162. __decorate([
  75163. BABYLON.serialize()
  75164. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  75165. return GridMaterial;
  75166. }(BABYLON.PushMaterial));
  75167. BABYLON.GridMaterial = GridMaterial;
  75168. })(BABYLON || (BABYLON = {}));
  75169. //# sourceMappingURL=babylon.gridmaterial.js.map
  75170. 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}";
  75171. 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}";
  75172. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75173. var BABYLON;
  75174. (function (BABYLON) {
  75175. /**
  75176. * Background material defines definition.
  75177. */
  75178. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  75179. __extends(BackgroundMaterialDefines, _super);
  75180. /**
  75181. * Constructor of the defines.
  75182. */
  75183. function BackgroundMaterialDefines() {
  75184. var _this = _super.call(this) || this;
  75185. /**
  75186. * True if the diffuse texture is in use.
  75187. */
  75188. _this.DIFFUSE = false;
  75189. /**
  75190. * The direct UV channel to use.
  75191. */
  75192. _this.DIFFUSEDIRECTUV = 0;
  75193. /**
  75194. * True if the diffuse texture is in gamma space.
  75195. */
  75196. _this.GAMMADIFFUSE = false;
  75197. /**
  75198. * True if the diffuse texture has opacity in the alpha channel.
  75199. */
  75200. _this.DIFFUSEHASALPHA = false;
  75201. /**
  75202. * True if you want the material to fade to transparent at grazing angle.
  75203. */
  75204. _this.OPACITYFRESNEL = false;
  75205. /**
  75206. * True if an extra blur needs to be added in the reflection.
  75207. */
  75208. _this.REFLECTIONBLUR = false;
  75209. /**
  75210. * False if the current Webgl implementation does not support the texture lod extension.
  75211. */
  75212. _this.TEXTURELODSUPPORT = false;
  75213. /**
  75214. * True to ensure the data are premultiplied.
  75215. */
  75216. _this.PREMULTIPLYALPHA = false;
  75217. /**
  75218. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  75219. */
  75220. _this.USERGBCOLOR = false;
  75221. // Image Processing Configuration.
  75222. _this.IMAGEPROCESSING = false;
  75223. _this.VIGNETTE = false;
  75224. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  75225. _this.VIGNETTEBLENDMODEOPAQUE = false;
  75226. _this.TONEMAPPING = false;
  75227. _this.CONTRAST = false;
  75228. _this.COLORCURVES = false;
  75229. _this.COLORGRADING = false;
  75230. _this.COLORGRADING3D = false;
  75231. _this.SAMPLER3DGREENDEPTH = false;
  75232. _this.SAMPLER3DBGRMAP = false;
  75233. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  75234. _this.EXPOSURE = false;
  75235. // Reflection.
  75236. _this.REFLECTION = false;
  75237. _this.REFLECTIONMAP_3D = false;
  75238. _this.REFLECTIONMAP_SPHERICAL = false;
  75239. _this.REFLECTIONMAP_PLANAR = false;
  75240. _this.REFLECTIONMAP_CUBIC = false;
  75241. _this.REFLECTIONMAP_PROJECTION = false;
  75242. _this.REFLECTIONMAP_SKYBOX = false;
  75243. _this.REFLECTIONMAP_EXPLICIT = false;
  75244. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75245. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75246. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75247. _this.INVERTCUBICMAP = false;
  75248. _this.REFLECTIONMAP_OPPOSITEZ = false;
  75249. _this.LODINREFLECTIONALPHA = false;
  75250. _this.GAMMAREFLECTION = false;
  75251. // Default BJS.
  75252. _this.MAINUV1 = false;
  75253. _this.MAINUV2 = false;
  75254. _this.UV1 = false;
  75255. _this.UV2 = false;
  75256. _this.CLIPPLANE = false;
  75257. _this.POINTSIZE = false;
  75258. _this.FOG = false;
  75259. _this.NORMAL = false;
  75260. _this.NUM_BONE_INFLUENCERS = 0;
  75261. _this.BonesPerMesh = 0;
  75262. _this.INSTANCES = false;
  75263. _this.SHADOWFLOAT = false;
  75264. _this.rebuild();
  75265. return _this;
  75266. }
  75267. return BackgroundMaterialDefines;
  75268. }(BABYLON.MaterialDefines));
  75269. /**
  75270. * Background material
  75271. */
  75272. var BackgroundMaterial = /** @class */ (function (_super) {
  75273. __extends(BackgroundMaterial, _super);
  75274. /**
  75275. * constructor
  75276. * @param name The name of the material
  75277. * @param scene The scene to add the material to
  75278. */
  75279. function BackgroundMaterial(name, scene) {
  75280. var _this = _super.call(this, name, scene) || this;
  75281. _this.primaryColor = BABYLON.Color3.White();
  75282. _this.primaryLevel = 1;
  75283. _this.secondaryColor = BABYLON.Color3.Gray();
  75284. _this.secondaryLevel = 1;
  75285. _this.tertiaryColor = BABYLON.Color3.Black();
  75286. _this.tertiaryLevel = 1;
  75287. _this.reflectionTexture = null;
  75288. _this.reflectionBlur = 0;
  75289. _this.diffuseTexture = null;
  75290. /**
  75291. * Specify the list of lights casting shadow on the material.
  75292. * All scene shadow lights will be included if null.
  75293. */
  75294. _this._shadowLights = null;
  75295. _this.shadowLights = null;
  75296. _this.shadowBlurScale = 1;
  75297. _this.shadowLevel = 0;
  75298. _this.opacityFresnel = true;
  75299. _this.useRGBColor = true;
  75300. /**
  75301. * Number of Simultaneous lights allowed on the material.
  75302. */
  75303. _this._maxSimultaneousLights = 4;
  75304. _this.maxSimultaneousLights = 4;
  75305. /**
  75306. * Keep track of the image processing observer to allow dispose and replace.
  75307. */
  75308. _this._imageProcessingObserver = null;
  75309. // Temp values kept as cache in the material.
  75310. _this._renderTargets = new BABYLON.SmartArray(16);
  75311. // Setup the default processing configuration to the scene.
  75312. _this._attachImageProcessingConfiguration(null);
  75313. _this.getRenderTargetTextures = function () {
  75314. _this._renderTargets.reset();
  75315. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  75316. _this._renderTargets.push(_this._diffuseTexture);
  75317. }
  75318. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  75319. _this._renderTargets.push(_this._reflectionTexture);
  75320. }
  75321. return _this._renderTargets;
  75322. };
  75323. return _this;
  75324. }
  75325. /**
  75326. * Attaches a new image processing configuration to the PBR Material.
  75327. * @param configuration (if null the scene configuration will be use)
  75328. */
  75329. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  75330. var _this = this;
  75331. if (configuration === this._imageProcessingConfiguration) {
  75332. return;
  75333. }
  75334. // Detaches observer.
  75335. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75336. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75337. }
  75338. // Pick the scene configuration if needed.
  75339. if (!configuration) {
  75340. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  75341. }
  75342. else {
  75343. this._imageProcessingConfiguration = configuration;
  75344. }
  75345. // Attaches observer.
  75346. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75347. _this._markAllSubMeshesAsImageProcessingDirty();
  75348. });
  75349. };
  75350. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  75351. /**
  75352. * Gets the image processing configuration used either in this material.
  75353. */
  75354. get: function () {
  75355. return this._imageProcessingConfiguration;
  75356. },
  75357. /**
  75358. * Sets the Default image processing configuration used either in the this material.
  75359. *
  75360. * If sets to null, the scene one is in use.
  75361. */
  75362. set: function (value) {
  75363. this._attachImageProcessingConfiguration(value);
  75364. // Ensure the effect will be rebuilt.
  75365. this._markAllSubMeshesAsTexturesDirty();
  75366. },
  75367. enumerable: true,
  75368. configurable: true
  75369. });
  75370. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  75371. /**
  75372. * Gets wether the color curves effect is enabled.
  75373. */
  75374. get: function () {
  75375. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75376. },
  75377. /**
  75378. * Sets wether the color curves effect is enabled.
  75379. */
  75380. set: function (value) {
  75381. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75382. },
  75383. enumerable: true,
  75384. configurable: true
  75385. });
  75386. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  75387. /**
  75388. * Gets wether the color grading effect is enabled.
  75389. */
  75390. get: function () {
  75391. return this.imageProcessingConfiguration.colorGradingEnabled;
  75392. },
  75393. /**
  75394. * Gets wether the color grading effect is enabled.
  75395. */
  75396. set: function (value) {
  75397. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75398. },
  75399. enumerable: true,
  75400. configurable: true
  75401. });
  75402. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  75403. /**
  75404. * Gets wether tonemapping is enabled or not.
  75405. */
  75406. get: function () {
  75407. return this._imageProcessingConfiguration.toneMappingEnabled;
  75408. },
  75409. /**
  75410. * Sets wether tonemapping is enabled or not
  75411. */
  75412. set: function (value) {
  75413. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75414. },
  75415. enumerable: true,
  75416. configurable: true
  75417. });
  75418. ;
  75419. ;
  75420. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  75421. /**
  75422. * The camera exposure used on this material.
  75423. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75424. * This corresponds to a photographic exposure.
  75425. */
  75426. get: function () {
  75427. return this._imageProcessingConfiguration.exposure;
  75428. },
  75429. /**
  75430. * The camera exposure used on this material.
  75431. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75432. * This corresponds to a photographic exposure.
  75433. */
  75434. set: function (value) {
  75435. this._imageProcessingConfiguration.exposure = value;
  75436. },
  75437. enumerable: true,
  75438. configurable: true
  75439. });
  75440. ;
  75441. ;
  75442. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  75443. /**
  75444. * Gets The camera contrast used on this material.
  75445. */
  75446. get: function () {
  75447. return this._imageProcessingConfiguration.contrast;
  75448. },
  75449. /**
  75450. * Sets The camera contrast used on this material.
  75451. */
  75452. set: function (value) {
  75453. this._imageProcessingConfiguration.contrast = value;
  75454. },
  75455. enumerable: true,
  75456. configurable: true
  75457. });
  75458. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  75459. /**
  75460. * Gets the Color Grading 2D Lookup Texture.
  75461. */
  75462. get: function () {
  75463. return this._imageProcessingConfiguration.colorGradingTexture;
  75464. },
  75465. /**
  75466. * Sets the Color Grading 2D Lookup Texture.
  75467. */
  75468. set: function (value) {
  75469. this.imageProcessingConfiguration.colorGradingTexture = value;
  75470. },
  75471. enumerable: true,
  75472. configurable: true
  75473. });
  75474. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  75475. /**
  75476. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75477. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75478. * 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;
  75479. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75480. */
  75481. get: function () {
  75482. return this.imageProcessingConfiguration.colorCurves;
  75483. },
  75484. /**
  75485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75487. * 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;
  75488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75489. */
  75490. set: function (value) {
  75491. this.imageProcessingConfiguration.colorCurves = value;
  75492. },
  75493. enumerable: true,
  75494. configurable: true
  75495. });
  75496. /**
  75497. * The entire material has been created in order to prevent overdraw.
  75498. * @returns false
  75499. */
  75500. BackgroundMaterial.prototype.needAlphaTesting = function () {
  75501. return false;
  75502. };
  75503. /**
  75504. * The entire material has been created in order to prevent overdraw.
  75505. * @returns true if blending is enable
  75506. */
  75507. BackgroundMaterial.prototype.needAlphaBlending = function () {
  75508. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  75509. };
  75510. /**
  75511. * Checks wether the material is ready to be rendered for a given mesh.
  75512. * @param mesh The mesh to render
  75513. * @param subMesh The submesh to check against
  75514. * @param useInstances Specify wether or not the material is used with instances
  75515. */
  75516. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75517. var _this = this;
  75518. if (useInstances === void 0) { useInstances = false; }
  75519. if (subMesh.effect && this.isFrozen) {
  75520. if (this._wasPreviouslyReady) {
  75521. return true;
  75522. }
  75523. }
  75524. if (!subMesh._materialDefines) {
  75525. subMesh._materialDefines = new BackgroundMaterialDefines();
  75526. }
  75527. var scene = this.getScene();
  75528. var defines = subMesh._materialDefines;
  75529. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75530. if (defines._renderId === scene.getRenderId()) {
  75531. return true;
  75532. }
  75533. }
  75534. var engine = scene.getEngine();
  75535. // Lights
  75536. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  75537. defines._needNormals = true;
  75538. // Textures
  75539. if (defines._areTexturesDirty) {
  75540. defines._needUVs = false;
  75541. if (scene.texturesEnabled) {
  75542. if (scene.getEngine().getCaps().textureLOD) {
  75543. defines.TEXTURELODSUPPORT = true;
  75544. }
  75545. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75546. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  75547. return false;
  75548. }
  75549. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  75550. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  75551. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  75552. defines.OPACITYFRESNEL = this._opacityFresnel;
  75553. }
  75554. else {
  75555. defines.DIFFUSE = false;
  75556. defines.DIFFUSEHASALPHA = false;
  75557. defines.GAMMADIFFUSE = false;
  75558. defines.OPACITYFRESNEL = false;
  75559. }
  75560. var reflectionTexture = this._reflectionTexture;
  75561. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75562. if (!reflectionTexture.isReadyOrNotBlocking()) {
  75563. return false;
  75564. }
  75565. defines.REFLECTION = true;
  75566. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  75567. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  75568. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  75569. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75570. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75571. defines.INVERTCUBICMAP = true;
  75572. }
  75573. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75574. switch (reflectionTexture.coordinatesMode) {
  75575. case BABYLON.Texture.CUBIC_MODE:
  75576. case BABYLON.Texture.INVCUBIC_MODE:
  75577. defines.REFLECTIONMAP_CUBIC = true;
  75578. break;
  75579. case BABYLON.Texture.EXPLICIT_MODE:
  75580. defines.REFLECTIONMAP_EXPLICIT = true;
  75581. break;
  75582. case BABYLON.Texture.PLANAR_MODE:
  75583. defines.REFLECTIONMAP_PLANAR = true;
  75584. break;
  75585. case BABYLON.Texture.PROJECTION_MODE:
  75586. defines.REFLECTIONMAP_PROJECTION = true;
  75587. break;
  75588. case BABYLON.Texture.SKYBOX_MODE:
  75589. defines.REFLECTIONMAP_SKYBOX = true;
  75590. break;
  75591. case BABYLON.Texture.SPHERICAL_MODE:
  75592. defines.REFLECTIONMAP_SPHERICAL = true;
  75593. break;
  75594. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75595. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75596. break;
  75597. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75598. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75599. break;
  75600. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75601. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75602. break;
  75603. }
  75604. }
  75605. else {
  75606. defines.REFLECTION = false;
  75607. defines.REFLECTIONBLUR = false;
  75608. defines.REFLECTIONMAP_3D = false;
  75609. defines.REFLECTIONMAP_SPHERICAL = false;
  75610. defines.REFLECTIONMAP_PLANAR = false;
  75611. defines.REFLECTIONMAP_CUBIC = false;
  75612. defines.REFLECTIONMAP_PROJECTION = false;
  75613. defines.REFLECTIONMAP_SKYBOX = false;
  75614. defines.REFLECTIONMAP_EXPLICIT = false;
  75615. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75616. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75617. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75618. defines.INVERTCUBICMAP = false;
  75619. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75620. defines.LODINREFLECTIONALPHA = false;
  75621. defines.GAMMAREFLECTION = false;
  75622. }
  75623. }
  75624. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75625. defines.USERGBCOLOR = this._useRGBColor;
  75626. }
  75627. if (defines._areImageProcessingDirty) {
  75628. if (!this._imageProcessingConfiguration.isReady()) {
  75629. return false;
  75630. }
  75631. this._imageProcessingConfiguration.prepareDefines(defines);
  75632. }
  75633. // Misc.
  75634. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75635. // Values that need to be evaluated on every frame
  75636. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75637. // Attribs
  75638. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75639. if (mesh) {
  75640. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75641. mesh.createNormals(true);
  75642. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75643. }
  75644. }
  75645. }
  75646. // Get correct effect
  75647. if (defines.isDirty) {
  75648. defines.markAsProcessed();
  75649. scene.resetCachedMaterial();
  75650. // Fallbacks
  75651. var fallbacks = new BABYLON.EffectFallbacks();
  75652. if (defines.FOG) {
  75653. fallbacks.addFallback(0, "FOG");
  75654. }
  75655. if (defines.POINTSIZE) {
  75656. fallbacks.addFallback(1, "POINTSIZE");
  75657. }
  75658. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75659. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75660. fallbacks.addCPUSkinningFallback(0, mesh);
  75661. }
  75662. //Attributes
  75663. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75664. if (defines.NORMAL) {
  75665. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75666. }
  75667. if (defines.UV1) {
  75668. attribs.push(BABYLON.VertexBuffer.UVKind);
  75669. }
  75670. if (defines.UV2) {
  75671. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75672. }
  75673. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75674. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75675. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75676. "vFogInfos", "vFogColor", "pointSize",
  75677. "vClipPlane", "mBones",
  75678. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75679. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75680. "shadowLevel", "alpha",
  75681. "vDiffuseInfos", "diffuseMatrix",
  75682. ];
  75683. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75684. var uniformBuffers = ["Material", "Scene"];
  75685. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75686. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75687. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75688. uniformsNames: uniforms,
  75689. uniformBuffersNames: uniformBuffers,
  75690. samplers: samplers,
  75691. defines: defines,
  75692. maxSimultaneousLights: this._maxSimultaneousLights
  75693. });
  75694. var onCompiled = function (effect) {
  75695. if (_this.onCompiled) {
  75696. _this.onCompiled(effect);
  75697. }
  75698. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75699. };
  75700. var join = defines.toString();
  75701. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75702. attributes: attribs,
  75703. uniformsNames: uniforms,
  75704. uniformBuffersNames: uniformBuffers,
  75705. samplers: samplers,
  75706. defines: join,
  75707. fallbacks: fallbacks,
  75708. onCompiled: onCompiled,
  75709. onError: this.onError,
  75710. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75711. }, engine), defines);
  75712. this.buildUniformLayout();
  75713. }
  75714. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75715. return false;
  75716. }
  75717. defines._renderId = scene.getRenderId();
  75718. this._wasPreviouslyReady = true;
  75719. return true;
  75720. };
  75721. /**
  75722. * Build the uniform buffer used in the material.
  75723. */
  75724. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75725. // Order is important !
  75726. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75727. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75728. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75729. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75730. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75731. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75732. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75733. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75734. this._uniformBuffer.addUniform("pointSize", 1);
  75735. this._uniformBuffer.addUniform("shadowLevel", 1);
  75736. this._uniformBuffer.addUniform("alpha", 1);
  75737. this._uniformBuffer.create();
  75738. };
  75739. /**
  75740. * Unbind the material.
  75741. */
  75742. BackgroundMaterial.prototype.unbind = function () {
  75743. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75744. this._uniformBuffer.setTexture("diffuseSampler", null);
  75745. }
  75746. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75747. this._uniformBuffer.setTexture("reflectionSampler", null);
  75748. }
  75749. _super.prototype.unbind.call(this);
  75750. };
  75751. /**
  75752. * Bind only the world matrix to the material.
  75753. * @param world The world matrix to bind.
  75754. */
  75755. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75756. this._activeEffect.setMatrix("world", world);
  75757. };
  75758. /**
  75759. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75760. * @param world The world matrix to bind.
  75761. * @param subMesh The submesh to bind for.
  75762. */
  75763. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75764. var scene = this.getScene();
  75765. var defines = subMesh._materialDefines;
  75766. if (!defines) {
  75767. return;
  75768. }
  75769. var effect = subMesh.effect;
  75770. if (!effect) {
  75771. return;
  75772. }
  75773. this._activeEffect = effect;
  75774. // Matrices
  75775. this.bindOnlyWorldMatrix(world);
  75776. // Bones
  75777. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75778. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75779. if (mustRebind) {
  75780. this._uniformBuffer.bindToEffect(effect, "Material");
  75781. this.bindViewProjection(effect);
  75782. var reflectionTexture = this._reflectionTexture;
  75783. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75784. // Texture uniforms
  75785. if (scene.texturesEnabled) {
  75786. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75787. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75788. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75789. }
  75790. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75791. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75792. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75793. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75794. }
  75795. }
  75796. if (this.shadowLevel > 0) {
  75797. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75798. }
  75799. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75800. // Point size
  75801. if (this.pointsCloud) {
  75802. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75803. }
  75804. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75805. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75806. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75807. }
  75808. // Textures
  75809. if (scene.texturesEnabled) {
  75810. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75811. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75812. }
  75813. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75814. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75815. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75816. }
  75817. else if (!defines.REFLECTIONBLUR) {
  75818. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75819. }
  75820. else {
  75821. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75822. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75823. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75824. }
  75825. }
  75826. }
  75827. // Clip plane
  75828. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75829. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75830. }
  75831. if (mustRebind || !this.isFrozen) {
  75832. if (scene.lightsEnabled) {
  75833. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75834. }
  75835. // View
  75836. this.bindView(effect);
  75837. // Fog
  75838. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75839. // image processing
  75840. this._imageProcessingConfiguration.bind(this._activeEffect);
  75841. }
  75842. this._uniformBuffer.update();
  75843. this._afterBind(mesh);
  75844. };
  75845. /**
  75846. * Dispose the material.
  75847. * @forceDisposeEffect Force disposal of the associated effect.
  75848. * @forceDisposeTextures Force disposal of the associated textures.
  75849. */
  75850. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75851. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75852. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75853. if (forceDisposeTextures) {
  75854. if (this.diffuseTexture) {
  75855. this.diffuseTexture.dispose();
  75856. }
  75857. if (this.reflectionTexture) {
  75858. this.reflectionTexture.dispose();
  75859. }
  75860. }
  75861. this._renderTargets.dispose();
  75862. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75863. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75864. }
  75865. _super.prototype.dispose.call(this, forceDisposeEffect);
  75866. };
  75867. /**
  75868. * Clones the material.
  75869. * @name The cloned name.
  75870. * @returns The cloned material.
  75871. */
  75872. BackgroundMaterial.prototype.clone = function (name) {
  75873. var _this = this;
  75874. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75875. };
  75876. /**
  75877. * Serializes the current material to its JSON representation.
  75878. * @returns The JSON representation.
  75879. */
  75880. BackgroundMaterial.prototype.serialize = function () {
  75881. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75882. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75883. return serializationObject;
  75884. };
  75885. /**
  75886. * Gets the class name of the material
  75887. * @returns "BackgroundMaterial"
  75888. */
  75889. BackgroundMaterial.prototype.getClassName = function () {
  75890. return "BackgroundMaterial";
  75891. };
  75892. /**
  75893. * Parse a JSON input to create back a background material.
  75894. * @param source
  75895. * @param scene
  75896. * @param rootUrl
  75897. * @returns the instantiated BackgroundMaterial.
  75898. */
  75899. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75900. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75901. };
  75902. __decorate([
  75903. BABYLON.serializeAsColor3()
  75904. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75905. __decorate([
  75906. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75907. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75908. __decorate([
  75909. BABYLON.serialize()
  75910. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75911. __decorate([
  75912. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75913. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75914. __decorate([
  75915. BABYLON.serializeAsColor3()
  75916. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75917. __decorate([
  75918. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75919. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75920. __decorate([
  75921. BABYLON.serialize()
  75922. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75923. __decorate([
  75924. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75925. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75926. __decorate([
  75927. BABYLON.serializeAsColor3()
  75928. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  75929. __decorate([
  75930. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75931. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  75932. __decorate([
  75933. BABYLON.serialize()
  75934. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  75935. __decorate([
  75936. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75937. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  75938. __decorate([
  75939. BABYLON.serializeAsTexture()
  75940. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75941. __decorate([
  75942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75943. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75944. __decorate([
  75945. BABYLON.serialize()
  75946. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75947. __decorate([
  75948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75949. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75950. __decorate([
  75951. BABYLON.serializeAsTexture()
  75952. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75953. __decorate([
  75954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75955. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75956. __decorate([
  75957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75958. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75959. __decorate([
  75960. BABYLON.serialize()
  75961. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75962. __decorate([
  75963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75964. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75965. __decorate([
  75966. BABYLON.serialize()
  75967. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  75968. __decorate([
  75969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75970. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  75971. __decorate([
  75972. BABYLON.serialize()
  75973. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  75974. __decorate([
  75975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75976. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  75977. __decorate([
  75978. BABYLON.serialize()
  75979. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  75980. __decorate([
  75981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75982. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  75983. __decorate([
  75984. BABYLON.serialize()
  75985. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  75986. __decorate([
  75987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75988. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  75989. __decorate([
  75990. BABYLON.serializeAsImageProcessingConfiguration()
  75991. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  75992. return BackgroundMaterial;
  75993. }(BABYLON.PushMaterial));
  75994. BABYLON.BackgroundMaterial = BackgroundMaterial;
  75995. })(BABYLON || (BABYLON = {}));
  75996. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  75997. 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";
  75998. 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}";
  75999. 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";
  76000. 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};";
  76001. 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";
  76002. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  76003. var BABYLON;
  76004. (function (BABYLON) {
  76005. var GLTFLoaderCoordinateSystemMode;
  76006. (function (GLTFLoaderCoordinateSystemMode) {
  76007. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  76008. // 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.
  76009. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  76010. // The glTF right-handed data is not transformed in any form and is loaded directly.
  76011. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  76012. // Sets the useRightHandedSystem flag on the scene.
  76013. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  76014. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  76015. var GLTFFileLoader = /** @class */ (function () {
  76016. function GLTFFileLoader() {
  76017. // V2 options
  76018. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  76019. this.name = "gltf";
  76020. this.extensions = {
  76021. ".gltf": { isBinary: false },
  76022. ".glb": { isBinary: true }
  76023. };
  76024. }
  76025. GLTFFileLoader.prototype.dispose = function () {
  76026. if (this._loader) {
  76027. this._loader.dispose();
  76028. }
  76029. };
  76030. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  76031. try {
  76032. var loaderData = GLTFFileLoader._parse(data);
  76033. if (this.onParsed) {
  76034. this.onParsed(loaderData);
  76035. }
  76036. this._loader = this._getLoader(loaderData);
  76037. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  76038. }
  76039. catch (e) {
  76040. onError(e.message);
  76041. }
  76042. };
  76043. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  76044. try {
  76045. var loaderData = GLTFFileLoader._parse(data);
  76046. if (this.onParsed) {
  76047. this.onParsed(loaderData);
  76048. }
  76049. this._loader = this._getLoader(loaderData);
  76050. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  76051. }
  76052. catch (e) {
  76053. onError(e.message);
  76054. }
  76055. };
  76056. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  76057. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  76058. };
  76059. GLTFFileLoader._parse = function (data) {
  76060. if (data instanceof ArrayBuffer) {
  76061. return GLTFFileLoader._parseBinary(data);
  76062. }
  76063. return {
  76064. json: JSON.parse(data),
  76065. bin: null
  76066. };
  76067. };
  76068. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  76069. var loaderVersion = { major: 2, minor: 0 };
  76070. var asset = loaderData.json.asset || {};
  76071. var version = GLTFFileLoader._parseVersion(asset.version);
  76072. if (!version) {
  76073. throw new Error("Invalid version: " + asset.version);
  76074. }
  76075. if (asset.minVersion !== undefined) {
  76076. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  76077. if (!minVersion) {
  76078. throw new Error("Invalid minimum version: " + asset.minVersion);
  76079. }
  76080. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  76081. throw new Error("Incompatible minimum version: " + asset.minVersion);
  76082. }
  76083. }
  76084. var createLoaders = {
  76085. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  76086. 2: GLTFFileLoader.CreateGLTFLoaderV2
  76087. };
  76088. var createLoader = createLoaders[version.major];
  76089. if (!createLoader) {
  76090. throw new Error("Unsupported version: " + asset.version);
  76091. }
  76092. return createLoader(this);
  76093. };
  76094. GLTFFileLoader._parseBinary = function (data) {
  76095. var Binary = {
  76096. Magic: 0x46546C67
  76097. };
  76098. var binaryReader = new BinaryReader(data);
  76099. var magic = binaryReader.readUint32();
  76100. if (magic !== Binary.Magic) {
  76101. throw new Error("Unexpected magic: " + magic);
  76102. }
  76103. var version = binaryReader.readUint32();
  76104. switch (version) {
  76105. case 1: return GLTFFileLoader._parseV1(binaryReader);
  76106. case 2: return GLTFFileLoader._parseV2(binaryReader);
  76107. }
  76108. throw new Error("Unsupported version: " + version);
  76109. };
  76110. GLTFFileLoader._parseV1 = function (binaryReader) {
  76111. var ContentFormat = {
  76112. JSON: 0
  76113. };
  76114. var length = binaryReader.readUint32();
  76115. if (length != binaryReader.getLength()) {
  76116. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76117. }
  76118. var contentLength = binaryReader.readUint32();
  76119. var contentFormat = binaryReader.readUint32();
  76120. var content;
  76121. switch (contentFormat) {
  76122. case ContentFormat.JSON: {
  76123. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  76124. break;
  76125. }
  76126. default: {
  76127. throw new Error("Unexpected content format: " + contentFormat);
  76128. }
  76129. }
  76130. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  76131. var body = binaryReader.readUint8Array(bytesRemaining);
  76132. return {
  76133. json: content,
  76134. bin: body
  76135. };
  76136. };
  76137. GLTFFileLoader._parseV2 = function (binaryReader) {
  76138. var ChunkFormat = {
  76139. JSON: 0x4E4F534A,
  76140. BIN: 0x004E4942
  76141. };
  76142. var length = binaryReader.readUint32();
  76143. if (length !== binaryReader.getLength()) {
  76144. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76145. }
  76146. // JSON chunk
  76147. var chunkLength = binaryReader.readUint32();
  76148. var chunkFormat = binaryReader.readUint32();
  76149. if (chunkFormat !== ChunkFormat.JSON) {
  76150. throw new Error("First chunk format is not JSON");
  76151. }
  76152. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  76153. // Look for BIN chunk
  76154. var bin = null;
  76155. while (binaryReader.getPosition() < binaryReader.getLength()) {
  76156. var chunkLength_1 = binaryReader.readUint32();
  76157. var chunkFormat_1 = binaryReader.readUint32();
  76158. switch (chunkFormat_1) {
  76159. case ChunkFormat.JSON: {
  76160. throw new Error("Unexpected JSON chunk");
  76161. }
  76162. case ChunkFormat.BIN: {
  76163. bin = binaryReader.readUint8Array(chunkLength_1);
  76164. break;
  76165. }
  76166. default: {
  76167. // ignore unrecognized chunkFormat
  76168. binaryReader.skipBytes(chunkLength_1);
  76169. break;
  76170. }
  76171. }
  76172. }
  76173. return {
  76174. json: json,
  76175. bin: bin
  76176. };
  76177. };
  76178. GLTFFileLoader._parseVersion = function (version) {
  76179. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  76180. if (!match) {
  76181. return null;
  76182. }
  76183. return {
  76184. major: parseInt(match[1]),
  76185. minor: parseInt(match[2])
  76186. };
  76187. };
  76188. GLTFFileLoader._compareVersion = function (a, b) {
  76189. if (a.major > b.major)
  76190. return 1;
  76191. if (a.major < b.major)
  76192. return -1;
  76193. if (a.minor > b.minor)
  76194. return 1;
  76195. if (a.minor < b.minor)
  76196. return -1;
  76197. return 0;
  76198. };
  76199. GLTFFileLoader._decodeBufferToText = function (buffer) {
  76200. var result = "";
  76201. var length = buffer.byteLength;
  76202. for (var i = 0; i < length; i++) {
  76203. result += String.fromCharCode(buffer[i]);
  76204. }
  76205. return result;
  76206. };
  76207. // V1 options
  76208. GLTFFileLoader.HomogeneousCoordinates = false;
  76209. GLTFFileLoader.IncrementalLoading = true;
  76210. return GLTFFileLoader;
  76211. }());
  76212. BABYLON.GLTFFileLoader = GLTFFileLoader;
  76213. var BinaryReader = /** @class */ (function () {
  76214. function BinaryReader(arrayBuffer) {
  76215. this._arrayBuffer = arrayBuffer;
  76216. this._dataView = new DataView(arrayBuffer);
  76217. this._byteOffset = 0;
  76218. }
  76219. BinaryReader.prototype.getPosition = function () {
  76220. return this._byteOffset;
  76221. };
  76222. BinaryReader.prototype.getLength = function () {
  76223. return this._arrayBuffer.byteLength;
  76224. };
  76225. BinaryReader.prototype.readUint32 = function () {
  76226. var value = this._dataView.getUint32(this._byteOffset, true);
  76227. this._byteOffset += 4;
  76228. return value;
  76229. };
  76230. BinaryReader.prototype.readUint8Array = function (length) {
  76231. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  76232. this._byteOffset += length;
  76233. return value;
  76234. };
  76235. BinaryReader.prototype.skipBytes = function (length) {
  76236. this._byteOffset += length;
  76237. };
  76238. return BinaryReader;
  76239. }());
  76240. if (BABYLON.SceneLoader) {
  76241. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  76242. }
  76243. })(BABYLON || (BABYLON = {}));
  76244. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  76245. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76246. var BABYLON;
  76247. (function (BABYLON) {
  76248. var GLTF1;
  76249. (function (GLTF1) {
  76250. /**
  76251. * Enums
  76252. */
  76253. var EComponentType;
  76254. (function (EComponentType) {
  76255. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  76256. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76257. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  76258. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76259. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  76260. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  76261. var EShaderType;
  76262. (function (EShaderType) {
  76263. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  76264. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  76265. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  76266. var EParameterType;
  76267. (function (EParameterType) {
  76268. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  76269. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76270. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  76271. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76272. EParameterType[EParameterType["INT"] = 5124] = "INT";
  76273. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  76274. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  76275. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  76276. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  76277. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  76278. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  76279. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  76280. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  76281. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  76282. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  76283. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  76284. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  76285. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  76286. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  76287. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  76288. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  76289. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  76290. var ETextureWrapMode;
  76291. (function (ETextureWrapMode) {
  76292. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  76293. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  76294. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  76295. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  76296. var ETextureFilterType;
  76297. (function (ETextureFilterType) {
  76298. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  76299. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  76300. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  76301. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  76302. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  76303. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  76304. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  76305. var ETextureFormat;
  76306. (function (ETextureFormat) {
  76307. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  76308. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  76309. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  76310. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  76311. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  76312. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  76313. var ECullingType;
  76314. (function (ECullingType) {
  76315. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  76316. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  76317. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  76318. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  76319. var EBlendingFunction;
  76320. (function (EBlendingFunction) {
  76321. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76322. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  76323. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  76324. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  76325. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  76326. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  76327. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  76328. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  76329. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  76330. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  76331. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  76332. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  76333. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  76334. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  76335. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  76336. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  76337. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  76338. })(BABYLON || (BABYLON = {}));
  76339. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  76340. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76341. var BABYLON;
  76342. (function (BABYLON) {
  76343. var GLTF1;
  76344. (function (GLTF1) {
  76345. /**
  76346. * Tokenizer. Used for shaders compatibility
  76347. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  76348. */
  76349. var ETokenType;
  76350. (function (ETokenType) {
  76351. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  76352. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  76353. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  76354. })(ETokenType || (ETokenType = {}));
  76355. var Tokenizer = /** @class */ (function () {
  76356. function Tokenizer(toParse) {
  76357. this._pos = 0;
  76358. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  76359. this._toParse = toParse;
  76360. this._maxPos = toParse.length;
  76361. }
  76362. Tokenizer.prototype.getNextToken = function () {
  76363. if (this.isEnd())
  76364. return ETokenType.END_OF_INPUT;
  76365. this.currentString = this.read();
  76366. this.currentToken = ETokenType.UNKNOWN;
  76367. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  76368. this.currentToken = ETokenType.IDENTIFIER;
  76369. this.currentIdentifier = this.currentString;
  76370. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  76371. this.currentIdentifier += this.currentString;
  76372. this.forward();
  76373. }
  76374. }
  76375. return this.currentToken;
  76376. };
  76377. Tokenizer.prototype.peek = function () {
  76378. return this._toParse[this._pos];
  76379. };
  76380. Tokenizer.prototype.read = function () {
  76381. return this._toParse[this._pos++];
  76382. };
  76383. Tokenizer.prototype.forward = function () {
  76384. this._pos++;
  76385. };
  76386. Tokenizer.prototype.isEnd = function () {
  76387. return this._pos >= this._maxPos;
  76388. };
  76389. return Tokenizer;
  76390. }());
  76391. /**
  76392. * Values
  76393. */
  76394. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  76395. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  76396. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  76397. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  76398. /**
  76399. * Parse
  76400. */
  76401. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  76402. for (var buf in parsedBuffers) {
  76403. var parsedBuffer = parsedBuffers[buf];
  76404. gltfRuntime.buffers[buf] = parsedBuffer;
  76405. gltfRuntime.buffersCount++;
  76406. }
  76407. };
  76408. var parseShaders = function (parsedShaders, gltfRuntime) {
  76409. for (var sha in parsedShaders) {
  76410. var parsedShader = parsedShaders[sha];
  76411. gltfRuntime.shaders[sha] = parsedShader;
  76412. gltfRuntime.shaderscount++;
  76413. }
  76414. };
  76415. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  76416. for (var object in parsedObjects) {
  76417. var parsedObject = parsedObjects[object];
  76418. gltfRuntime[runtimeProperty][object] = parsedObject;
  76419. }
  76420. };
  76421. /**
  76422. * Utils
  76423. */
  76424. var normalizeUVs = function (buffer) {
  76425. if (!buffer) {
  76426. return;
  76427. }
  76428. for (var i = 0; i < buffer.length / 2; i++) {
  76429. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  76430. }
  76431. };
  76432. var getAttribute = function (attributeParameter) {
  76433. if (attributeParameter.semantic === "NORMAL") {
  76434. return "normal";
  76435. }
  76436. else if (attributeParameter.semantic === "POSITION") {
  76437. return "position";
  76438. }
  76439. else if (attributeParameter.semantic === "JOINT") {
  76440. return "matricesIndices";
  76441. }
  76442. else if (attributeParameter.semantic === "WEIGHT") {
  76443. return "matricesWeights";
  76444. }
  76445. else if (attributeParameter.semantic === "COLOR") {
  76446. return "color";
  76447. }
  76448. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  76449. var channel = Number(attributeParameter.semantic.split("_")[1]);
  76450. return "uv" + (channel === 0 ? "" : channel + 1);
  76451. }
  76452. return null;
  76453. };
  76454. /**
  76455. * Loads and creates animations
  76456. */
  76457. var loadAnimations = function (gltfRuntime) {
  76458. for (var anim in gltfRuntime.animations) {
  76459. var animation = gltfRuntime.animations[anim];
  76460. if (!animation.channels || !animation.samplers) {
  76461. continue;
  76462. }
  76463. var lastAnimation = null;
  76464. for (var i = 0; i < animation.channels.length; i++) {
  76465. // Get parameters and load buffers
  76466. var channel = animation.channels[i];
  76467. var sampler = animation.samplers[channel.sampler];
  76468. if (!sampler) {
  76469. continue;
  76470. }
  76471. var inputData = null;
  76472. var outputData = null;
  76473. if (animation.parameters) {
  76474. inputData = animation.parameters[sampler.input];
  76475. outputData = animation.parameters[sampler.output];
  76476. }
  76477. else {
  76478. inputData = sampler.input;
  76479. outputData = sampler.output;
  76480. }
  76481. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  76482. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  76483. var targetID = channel.target.id;
  76484. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  76485. if (targetNode === null) {
  76486. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  76487. }
  76488. if (targetNode === null) {
  76489. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  76490. continue;
  76491. }
  76492. var isBone = targetNode instanceof BABYLON.Bone;
  76493. // Get target path (position, rotation or scaling)
  76494. var targetPath = channel.target.path;
  76495. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  76496. if (targetPathIndex !== -1) {
  76497. targetPath = babylonAnimationPaths[targetPathIndex];
  76498. }
  76499. // Determine animation type
  76500. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  76501. if (!isBone) {
  76502. if (targetPath === "rotationQuaternion") {
  76503. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  76504. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  76505. }
  76506. else {
  76507. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  76508. }
  76509. }
  76510. // Create animation and key frames
  76511. var babylonAnimation = null;
  76512. var keys = [];
  76513. var arrayOffset = 0;
  76514. var modifyKey = false;
  76515. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  76516. babylonAnimation = lastAnimation;
  76517. modifyKey = true;
  76518. }
  76519. if (!modifyKey) {
  76520. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76521. }
  76522. // For each frame
  76523. for (var j = 0; j < bufferInput.length; j++) {
  76524. var value = null;
  76525. if (targetPath === "rotationQuaternion") {
  76526. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  76527. arrayOffset += 4;
  76528. }
  76529. else {
  76530. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  76531. arrayOffset += 3;
  76532. }
  76533. if (isBone) {
  76534. var bone = targetNode;
  76535. var translation = BABYLON.Vector3.Zero();
  76536. var rotationQuaternion = new BABYLON.Quaternion();
  76537. var scaling = BABYLON.Vector3.Zero();
  76538. // Warning on decompose
  76539. var mat = bone.getBaseMatrix();
  76540. if (modifyKey && lastAnimation) {
  76541. mat = lastAnimation.getKeys()[j].value;
  76542. }
  76543. mat.decompose(scaling, rotationQuaternion, translation);
  76544. if (targetPath === "position") {
  76545. translation = value;
  76546. }
  76547. else if (targetPath === "rotationQuaternion") {
  76548. rotationQuaternion = value;
  76549. }
  76550. else {
  76551. scaling = value;
  76552. }
  76553. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  76554. }
  76555. if (!modifyKey) {
  76556. keys.push({
  76557. frame: bufferInput[j],
  76558. value: value
  76559. });
  76560. }
  76561. else if (lastAnimation) {
  76562. lastAnimation.getKeys()[j].value = value;
  76563. }
  76564. }
  76565. // Finish
  76566. if (!modifyKey && babylonAnimation) {
  76567. babylonAnimation.setKeys(keys);
  76568. targetNode.animations.push(babylonAnimation);
  76569. }
  76570. lastAnimation = babylonAnimation;
  76571. gltfRuntime.scene.stopAnimation(targetNode);
  76572. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  76573. }
  76574. }
  76575. };
  76576. /**
  76577. * Returns the bones transformation matrix
  76578. */
  76579. var configureBoneTransformation = function (node) {
  76580. var mat = null;
  76581. if (node.translation || node.rotation || node.scale) {
  76582. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  76583. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  76584. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  76585. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  76586. }
  76587. else {
  76588. mat = BABYLON.Matrix.FromArray(node.matrix);
  76589. }
  76590. return mat;
  76591. };
  76592. /**
  76593. * Returns the parent bone
  76594. */
  76595. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  76596. // Try to find
  76597. for (var i = 0; i < newSkeleton.bones.length; i++) {
  76598. if (newSkeleton.bones[i].name === jointName) {
  76599. return newSkeleton.bones[i];
  76600. }
  76601. }
  76602. // Not found, search in gltf nodes
  76603. var nodes = gltfRuntime.nodes;
  76604. for (var nde in nodes) {
  76605. var node = nodes[nde];
  76606. if (!node.jointName) {
  76607. continue;
  76608. }
  76609. var children = node.children;
  76610. for (var i = 0; i < children.length; i++) {
  76611. var child = gltfRuntime.nodes[children[i]];
  76612. if (!child.jointName) {
  76613. continue;
  76614. }
  76615. if (child.jointName === jointName) {
  76616. var mat = configureBoneTransformation(node);
  76617. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76618. bone.id = nde;
  76619. return bone;
  76620. }
  76621. }
  76622. }
  76623. return null;
  76624. };
  76625. /**
  76626. * Returns the appropriate root node
  76627. */
  76628. var getNodeToRoot = function (nodesToRoot, id) {
  76629. for (var i = 0; i < nodesToRoot.length; i++) {
  76630. var nodeToRoot = nodesToRoot[i];
  76631. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76632. var child = nodeToRoot.node.children[j];
  76633. if (child === id) {
  76634. return nodeToRoot.bone;
  76635. }
  76636. }
  76637. }
  76638. return null;
  76639. };
  76640. /**
  76641. * Returns the node with the joint name
  76642. */
  76643. var getJointNode = function (gltfRuntime, jointName) {
  76644. var nodes = gltfRuntime.nodes;
  76645. var node = nodes[jointName];
  76646. if (node) {
  76647. return {
  76648. node: node,
  76649. id: jointName
  76650. };
  76651. }
  76652. for (var nde in nodes) {
  76653. node = nodes[nde];
  76654. if (node.jointName === jointName) {
  76655. return {
  76656. node: node,
  76657. id: nde
  76658. };
  76659. }
  76660. }
  76661. return null;
  76662. };
  76663. /**
  76664. * Checks if a nodes is in joints
  76665. */
  76666. var nodeIsInJoints = function (skins, id) {
  76667. for (var i = 0; i < skins.jointNames.length; i++) {
  76668. if (skins.jointNames[i] === id) {
  76669. return true;
  76670. }
  76671. }
  76672. return false;
  76673. };
  76674. /**
  76675. * Fills the nodes to root for bones and builds hierarchy
  76676. */
  76677. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76678. // Creates nodes for root
  76679. for (var nde in gltfRuntime.nodes) {
  76680. var node = gltfRuntime.nodes[nde];
  76681. var id = nde;
  76682. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76683. continue;
  76684. }
  76685. // Create node to root bone
  76686. var mat = configureBoneTransformation(node);
  76687. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76688. bone.id = id;
  76689. nodesToRoot.push({ bone: bone, node: node, id: id });
  76690. }
  76691. // Parenting
  76692. for (var i = 0; i < nodesToRoot.length; i++) {
  76693. var nodeToRoot = nodesToRoot[i];
  76694. var children = nodeToRoot.node.children;
  76695. for (var j = 0; j < children.length; j++) {
  76696. var child = null;
  76697. for (var k = 0; k < nodesToRoot.length; k++) {
  76698. if (nodesToRoot[k].id === children[j]) {
  76699. child = nodesToRoot[k];
  76700. break;
  76701. }
  76702. }
  76703. if (child) {
  76704. child.bone._parent = nodeToRoot.bone;
  76705. nodeToRoot.bone.children.push(child.bone);
  76706. }
  76707. }
  76708. }
  76709. };
  76710. /**
  76711. * Imports a skeleton
  76712. */
  76713. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76714. if (!newSkeleton) {
  76715. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76716. }
  76717. if (!skins.babylonSkeleton) {
  76718. return newSkeleton;
  76719. }
  76720. // Find the root bones
  76721. var nodesToRoot = [];
  76722. var nodesToRootToAdd = [];
  76723. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76724. newSkeleton.bones = [];
  76725. // Joints
  76726. for (var i = 0; i < skins.jointNames.length; i++) {
  76727. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76728. if (!jointNode) {
  76729. continue;
  76730. }
  76731. var node = jointNode.node;
  76732. if (!node) {
  76733. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76734. continue;
  76735. }
  76736. var id = jointNode.id;
  76737. // Optimize, if the bone already exists...
  76738. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76739. if (existingBone) {
  76740. newSkeleton.bones.push(existingBone);
  76741. continue;
  76742. }
  76743. // Search for parent bone
  76744. var foundBone = false;
  76745. var parentBone = null;
  76746. for (var j = 0; j < i; j++) {
  76747. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76748. if (!jointNode_1) {
  76749. continue;
  76750. }
  76751. var joint = jointNode_1.node;
  76752. if (!joint) {
  76753. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76754. continue;
  76755. }
  76756. var children = joint.children;
  76757. if (!children) {
  76758. continue;
  76759. }
  76760. foundBone = false;
  76761. for (var k = 0; k < children.length; k++) {
  76762. if (children[k] === id) {
  76763. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76764. foundBone = true;
  76765. break;
  76766. }
  76767. }
  76768. if (foundBone) {
  76769. break;
  76770. }
  76771. }
  76772. // Create bone
  76773. var mat = configureBoneTransformation(node);
  76774. if (!parentBone && nodesToRoot.length > 0) {
  76775. parentBone = getNodeToRoot(nodesToRoot, id);
  76776. if (parentBone) {
  76777. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76778. nodesToRootToAdd.push(parentBone);
  76779. }
  76780. }
  76781. }
  76782. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76783. bone.id = id;
  76784. }
  76785. // Polish
  76786. var bones = newSkeleton.bones;
  76787. newSkeleton.bones = [];
  76788. for (var i = 0; i < skins.jointNames.length; i++) {
  76789. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76790. if (!jointNode) {
  76791. continue;
  76792. }
  76793. for (var j = 0; j < bones.length; j++) {
  76794. if (bones[j].id === jointNode.id) {
  76795. newSkeleton.bones.push(bones[j]);
  76796. break;
  76797. }
  76798. }
  76799. }
  76800. newSkeleton.prepare();
  76801. // Finish
  76802. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76803. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76804. }
  76805. return newSkeleton;
  76806. };
  76807. /**
  76808. * Imports a mesh and its geometries
  76809. */
  76810. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76811. if (!newMesh) {
  76812. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76813. newMesh.id = id;
  76814. }
  76815. if (!node.babylonNode) {
  76816. return newMesh;
  76817. }
  76818. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  76819. if (!newMesh.material) {
  76820. newMesh.material = multiMat;
  76821. }
  76822. var vertexData = new BABYLON.VertexData();
  76823. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  76824. var verticesStarts = new Array();
  76825. var verticesCounts = new Array();
  76826. var indexStarts = new Array();
  76827. var indexCounts = new Array();
  76828. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76829. var meshID = meshes[meshIndex];
  76830. var mesh = gltfRuntime.meshes[meshID];
  76831. if (!mesh) {
  76832. continue;
  76833. }
  76834. // Positions, normals and UVs
  76835. for (var i = 0; i < mesh.primitives.length; i++) {
  76836. // Temporary vertex data
  76837. var tempVertexData = new BABYLON.VertexData();
  76838. var primitive = mesh.primitives[i];
  76839. if (primitive.mode !== 4) {
  76840. // continue;
  76841. }
  76842. var attributes = primitive.attributes;
  76843. var accessor = null;
  76844. var buffer = null;
  76845. // Set positions, normal and uvs
  76846. for (var semantic in attributes) {
  76847. // Link accessor and buffer view
  76848. accessor = gltfRuntime.accessors[attributes[semantic]];
  76849. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76850. if (semantic === "NORMAL") {
  76851. tempVertexData.normals = new Float32Array(buffer.length);
  76852. tempVertexData.normals.set(buffer);
  76853. }
  76854. else if (semantic === "POSITION") {
  76855. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  76856. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  76857. for (var j = 0; j < buffer.length; j += 4) {
  76858. tempVertexData.positions[j] = buffer[j];
  76859. tempVertexData.positions[j + 1] = buffer[j + 1];
  76860. tempVertexData.positions[j + 2] = buffer[j + 2];
  76861. }
  76862. }
  76863. else {
  76864. tempVertexData.positions = new Float32Array(buffer.length);
  76865. tempVertexData.positions.set(buffer);
  76866. }
  76867. verticesCounts.push(tempVertexData.positions.length);
  76868. }
  76869. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  76870. var channel = Number(semantic.split("_")[1]);
  76871. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  76872. var uvs = new Float32Array(buffer.length);
  76873. uvs.set(buffer);
  76874. normalizeUVs(uvs);
  76875. tempVertexData.set(uvs, uvKind);
  76876. }
  76877. else if (semantic === "JOINT") {
  76878. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  76879. tempVertexData.matricesIndices.set(buffer);
  76880. }
  76881. else if (semantic === "WEIGHT") {
  76882. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  76883. tempVertexData.matricesWeights.set(buffer);
  76884. }
  76885. else if (semantic === "COLOR") {
  76886. tempVertexData.colors = new Float32Array(buffer.length);
  76887. tempVertexData.colors.set(buffer);
  76888. }
  76889. }
  76890. // Indices
  76891. accessor = gltfRuntime.accessors[primitive.indices];
  76892. if (accessor) {
  76893. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76894. tempVertexData.indices = new Int32Array(buffer.length);
  76895. tempVertexData.indices.set(buffer);
  76896. indexCounts.push(tempVertexData.indices.length);
  76897. }
  76898. else {
  76899. // Set indices on the fly
  76900. var indices = [];
  76901. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  76902. indices.push(j);
  76903. }
  76904. tempVertexData.indices = new Int32Array(indices);
  76905. indexCounts.push(tempVertexData.indices.length);
  76906. }
  76907. vertexData.merge(tempVertexData);
  76908. // Sub material
  76909. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  76910. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  76911. // Update vertices start and index start
  76912. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  76913. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  76914. }
  76915. }
  76916. // Apply geometry
  76917. geometry.setAllVerticesData(vertexData, false);
  76918. newMesh.computeWorldMatrix(true);
  76919. // Apply submeshes
  76920. newMesh.subMeshes = [];
  76921. var index = 0;
  76922. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76923. var meshID = meshes[meshIndex];
  76924. var mesh = gltfRuntime.meshes[meshID];
  76925. if (!mesh) {
  76926. continue;
  76927. }
  76928. for (var i = 0; i < mesh.primitives.length; i++) {
  76929. if (mesh.primitives[i].mode !== 4) {
  76930. //continue;
  76931. }
  76932. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  76933. index++;
  76934. }
  76935. }
  76936. // Finish
  76937. return newMesh;
  76938. };
  76939. /**
  76940. * Configure node transformation from position, rotation and scaling
  76941. */
  76942. var configureNode = function (newNode, position, rotation, scaling) {
  76943. if (newNode.position) {
  76944. newNode.position = position;
  76945. }
  76946. if (newNode.rotationQuaternion || newNode.rotation) {
  76947. newNode.rotationQuaternion = rotation;
  76948. }
  76949. if (newNode.scaling) {
  76950. newNode.scaling = scaling;
  76951. }
  76952. };
  76953. /**
  76954. * Configures node from transformation matrix
  76955. */
  76956. var configureNodeFromMatrix = function (newNode, node, parent) {
  76957. if (node.matrix) {
  76958. var position = new BABYLON.Vector3(0, 0, 0);
  76959. var rotation = new BABYLON.Quaternion();
  76960. var scaling = new BABYLON.Vector3(0, 0, 0);
  76961. var mat = BABYLON.Matrix.FromArray(node.matrix);
  76962. mat.decompose(scaling, rotation, position);
  76963. configureNode(newNode, position, rotation, scaling);
  76964. }
  76965. else if (node.translation && node.rotation && node.scale) {
  76966. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  76967. }
  76968. newNode.computeWorldMatrix(true);
  76969. };
  76970. /**
  76971. * Imports a node
  76972. */
  76973. var importNode = function (gltfRuntime, node, id, parent) {
  76974. var lastNode = null;
  76975. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  76976. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  76977. return null;
  76978. }
  76979. }
  76980. // Meshes
  76981. if (node.skin) {
  76982. if (node.meshes) {
  76983. var skin = gltfRuntime.skins[node.skin];
  76984. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  76985. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  76986. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  76987. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  76988. if (!skin.babylonSkeleton) {
  76989. skin.babylonSkeleton = newMesh.skeleton;
  76990. }
  76991. }
  76992. lastNode = newMesh;
  76993. }
  76994. }
  76995. else if (node.meshes) {
  76996. /**
  76997. * Improve meshes property
  76998. */
  76999. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  77000. lastNode = newMesh;
  77001. }
  77002. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  77003. var light = gltfRuntime.lights[node.light];
  77004. if (light) {
  77005. if (light.type === "ambient") {
  77006. var ambienLight = light[light.type];
  77007. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77008. hemiLight.name = node.name || "";
  77009. if (ambienLight.color) {
  77010. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  77011. }
  77012. lastNode = hemiLight;
  77013. }
  77014. else if (light.type === "directional") {
  77015. var directionalLight = light[light.type];
  77016. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77017. dirLight.name = node.name || "";
  77018. if (directionalLight.color) {
  77019. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  77020. }
  77021. lastNode = dirLight;
  77022. }
  77023. else if (light.type === "point") {
  77024. var pointLight = light[light.type];
  77025. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77026. ptLight.name = node.name || "";
  77027. if (pointLight.color) {
  77028. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  77029. }
  77030. lastNode = ptLight;
  77031. }
  77032. else if (light.type === "spot") {
  77033. var spotLight = light[light.type];
  77034. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  77035. spLight.name = node.name || "";
  77036. if (spotLight.color) {
  77037. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  77038. }
  77039. if (spotLight.fallOfAngle) {
  77040. spLight.angle = spotLight.fallOfAngle;
  77041. }
  77042. if (spotLight.fallOffExponent) {
  77043. spLight.exponent = spotLight.fallOffExponent;
  77044. }
  77045. lastNode = spLight;
  77046. }
  77047. }
  77048. }
  77049. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  77050. var camera = gltfRuntime.cameras[node.camera];
  77051. if (camera) {
  77052. if (camera.type === "orthographic") {
  77053. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77054. orthoCamera.name = node.name || "";
  77055. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  77056. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77057. lastNode = orthoCamera;
  77058. }
  77059. else if (camera.type === "perspective") {
  77060. var perspectiveCamera = camera[camera.type];
  77061. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77062. persCamera.name = node.name || "";
  77063. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77064. if (!perspectiveCamera.aspectRatio) {
  77065. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  77066. }
  77067. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  77068. persCamera.maxZ = perspectiveCamera.zfar;
  77069. persCamera.minZ = perspectiveCamera.znear;
  77070. }
  77071. lastNode = persCamera;
  77072. }
  77073. }
  77074. }
  77075. // Empty node
  77076. if (!node.jointName) {
  77077. if (node.babylonNode) {
  77078. return node.babylonNode;
  77079. }
  77080. else if (lastNode === null) {
  77081. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  77082. node.babylonNode = dummy;
  77083. lastNode = dummy;
  77084. }
  77085. }
  77086. if (lastNode !== null) {
  77087. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  77088. configureNodeFromMatrix(lastNode, node, parent);
  77089. }
  77090. else {
  77091. var translation = node.translation || [0, 0, 0];
  77092. var rotation = node.rotation || [0, 0, 0, 1];
  77093. var scale = node.scale || [1, 1, 1];
  77094. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  77095. }
  77096. lastNode.updateCache(true);
  77097. node.babylonNode = lastNode;
  77098. }
  77099. return lastNode;
  77100. };
  77101. /**
  77102. * Traverses nodes and creates them
  77103. */
  77104. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  77105. if (meshIncluded === void 0) { meshIncluded = false; }
  77106. var node = gltfRuntime.nodes[id];
  77107. var newNode = null;
  77108. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  77109. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  77110. meshIncluded = true;
  77111. }
  77112. else {
  77113. meshIncluded = false;
  77114. }
  77115. }
  77116. else {
  77117. meshIncluded = true;
  77118. }
  77119. if (!node.jointName && meshIncluded) {
  77120. newNode = importNode(gltfRuntime, node, id, parent);
  77121. if (newNode !== null) {
  77122. newNode.id = id;
  77123. newNode.parent = parent;
  77124. }
  77125. }
  77126. if (node.children) {
  77127. for (var i = 0; i < node.children.length; i++) {
  77128. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  77129. }
  77130. }
  77131. };
  77132. /**
  77133. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  77134. */
  77135. var postLoad = function (gltfRuntime) {
  77136. // Nodes
  77137. var currentScene = gltfRuntime.currentScene;
  77138. if (currentScene) {
  77139. for (var i = 0; i < currentScene.nodes.length; i++) {
  77140. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77141. }
  77142. }
  77143. else {
  77144. for (var thing in gltfRuntime.scenes) {
  77145. currentScene = gltfRuntime.scenes[thing];
  77146. for (var i = 0; i < currentScene.nodes.length; i++) {
  77147. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77148. }
  77149. }
  77150. }
  77151. // Set animations
  77152. loadAnimations(gltfRuntime);
  77153. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  77154. var skeleton = gltfRuntime.scene.skeletons[i];
  77155. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  77156. }
  77157. };
  77158. /**
  77159. * onBind shaderrs callback to set uniforms and matrices
  77160. */
  77161. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  77162. var materialValues = material.values || technique.parameters;
  77163. for (var unif in unTreatedUniforms) {
  77164. var uniform = unTreatedUniforms[unif];
  77165. var type = uniform.type;
  77166. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  77167. if (uniform.semantic && !uniform.source && !uniform.node) {
  77168. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  77169. }
  77170. else if (uniform.semantic && (uniform.source || uniform.node)) {
  77171. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  77172. if (source === null) {
  77173. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  77174. }
  77175. if (source === null) {
  77176. continue;
  77177. }
  77178. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  77179. }
  77180. }
  77181. else {
  77182. var value = materialValues[technique.uniforms[unif]];
  77183. if (!value) {
  77184. continue;
  77185. }
  77186. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77187. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  77188. if (texture === null || texture === undefined) {
  77189. continue;
  77190. }
  77191. shaderMaterial.getEffect().setTexture(unif, texture);
  77192. }
  77193. else {
  77194. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  77195. }
  77196. }
  77197. }
  77198. onSuccess(shaderMaterial);
  77199. };
  77200. /**
  77201. * Prepare uniforms to send the only one time
  77202. * Loads the appropriate textures
  77203. */
  77204. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  77205. var materialValues = material.values || technique.parameters;
  77206. var techniqueUniforms = technique.uniforms;
  77207. /**
  77208. * Prepare values here (not matrices)
  77209. */
  77210. for (var unif in unTreatedUniforms) {
  77211. var uniform = unTreatedUniforms[unif];
  77212. var type = uniform.type;
  77213. var value = materialValues[techniqueUniforms[unif]];
  77214. if (value === undefined) {
  77215. // In case the value is the same for all materials
  77216. value = uniform.value;
  77217. }
  77218. if (!value) {
  77219. continue;
  77220. }
  77221. var onLoadTexture = function (uniformName) {
  77222. return function (texture) {
  77223. if (uniform.value && uniformName) {
  77224. // Static uniform
  77225. shaderMaterial.setTexture(uniformName, texture);
  77226. delete unTreatedUniforms[uniformName];
  77227. }
  77228. };
  77229. };
  77230. // Texture (sampler2D)
  77231. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77232. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  77233. }
  77234. else {
  77235. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  77236. // Static uniform
  77237. delete unTreatedUniforms[unif];
  77238. }
  77239. }
  77240. }
  77241. };
  77242. /**
  77243. * Shader compilation failed
  77244. */
  77245. var onShaderCompileError = function (program, shaderMaterial, onError) {
  77246. return function (effect, error) {
  77247. shaderMaterial.dispose(true);
  77248. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  77249. };
  77250. };
  77251. /**
  77252. * Shader compilation success
  77253. */
  77254. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  77255. return function (_) {
  77256. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  77257. shaderMaterial.onBind = function (mesh) {
  77258. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  77259. };
  77260. };
  77261. };
  77262. /**
  77263. * Returns the appropriate uniform if already handled by babylon
  77264. */
  77265. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  77266. for (var unif in technique.uniforms) {
  77267. var uniform = technique.uniforms[unif];
  77268. var uniformParameter = technique.parameters[uniform];
  77269. if (tokenizer.currentIdentifier === unif) {
  77270. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  77271. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77272. if (transformIndex !== -1) {
  77273. delete unTreatedUniforms[unif];
  77274. return babylonTransforms[transformIndex];
  77275. }
  77276. }
  77277. }
  77278. }
  77279. return tokenizer.currentIdentifier;
  77280. };
  77281. /**
  77282. * All shaders loaded. Create materials one by one
  77283. */
  77284. var importMaterials = function (gltfRuntime) {
  77285. // Create materials
  77286. for (var mat in gltfRuntime.materials) {
  77287. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  77288. }
  77289. };
  77290. /**
  77291. * Implementation of the base glTF spec
  77292. */
  77293. var GLTFLoaderBase = /** @class */ (function () {
  77294. function GLTFLoaderBase() {
  77295. }
  77296. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  77297. var gltfRuntime = {
  77298. extensions: {},
  77299. accessors: {},
  77300. buffers: {},
  77301. bufferViews: {},
  77302. meshes: {},
  77303. lights: {},
  77304. cameras: {},
  77305. nodes: {},
  77306. images: {},
  77307. textures: {},
  77308. shaders: {},
  77309. programs: {},
  77310. samplers: {},
  77311. techniques: {},
  77312. materials: {},
  77313. animations: {},
  77314. skins: {},
  77315. extensionsUsed: [],
  77316. scenes: {},
  77317. buffersCount: 0,
  77318. shaderscount: 0,
  77319. scene: scene,
  77320. rootUrl: rootUrl,
  77321. loadedBufferCount: 0,
  77322. loadedBufferViews: {},
  77323. loadedShaderCount: 0,
  77324. importOnlyMeshes: false,
  77325. dummyNodes: []
  77326. };
  77327. // Parse
  77328. if (parsedData.extensions) {
  77329. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  77330. }
  77331. if (parsedData.extensionsUsed) {
  77332. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  77333. }
  77334. if (parsedData.buffers) {
  77335. parseBuffers(parsedData.buffers, gltfRuntime);
  77336. }
  77337. if (parsedData.bufferViews) {
  77338. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  77339. }
  77340. if (parsedData.accessors) {
  77341. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  77342. }
  77343. if (parsedData.meshes) {
  77344. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  77345. }
  77346. if (parsedData.lights) {
  77347. parseObject(parsedData.lights, "lights", gltfRuntime);
  77348. }
  77349. if (parsedData.cameras) {
  77350. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  77351. }
  77352. if (parsedData.nodes) {
  77353. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  77354. }
  77355. if (parsedData.images) {
  77356. parseObject(parsedData.images, "images", gltfRuntime);
  77357. }
  77358. if (parsedData.textures) {
  77359. parseObject(parsedData.textures, "textures", gltfRuntime);
  77360. }
  77361. if (parsedData.shaders) {
  77362. parseShaders(parsedData.shaders, gltfRuntime);
  77363. }
  77364. if (parsedData.programs) {
  77365. parseObject(parsedData.programs, "programs", gltfRuntime);
  77366. }
  77367. if (parsedData.samplers) {
  77368. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  77369. }
  77370. if (parsedData.techniques) {
  77371. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  77372. }
  77373. if (parsedData.materials) {
  77374. parseObject(parsedData.materials, "materials", gltfRuntime);
  77375. }
  77376. if (parsedData.animations) {
  77377. parseObject(parsedData.animations, "animations", gltfRuntime);
  77378. }
  77379. if (parsedData.skins) {
  77380. parseObject(parsedData.skins, "skins", gltfRuntime);
  77381. }
  77382. if (parsedData.scenes) {
  77383. gltfRuntime.scenes = parsedData.scenes;
  77384. }
  77385. if (parsedData.scene && parsedData.scenes) {
  77386. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  77387. }
  77388. return gltfRuntime;
  77389. };
  77390. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77391. var buffer = gltfRuntime.buffers[id];
  77392. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  77393. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  77394. }
  77395. else {
  77396. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  77397. if (request) {
  77398. onError(request.status + " " + request.statusText);
  77399. }
  77400. });
  77401. }
  77402. };
  77403. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77404. var texture = gltfRuntime.textures[id];
  77405. if (!texture || !texture.source) {
  77406. onError("");
  77407. return;
  77408. }
  77409. if (texture.babylonTexture) {
  77410. onSuccess(null);
  77411. return;
  77412. }
  77413. var source = gltfRuntime.images[texture.source];
  77414. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  77415. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  77416. }
  77417. else {
  77418. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  77419. if (request) {
  77420. onError(request.status + " " + request.statusText);
  77421. }
  77422. });
  77423. }
  77424. };
  77425. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77426. var texture = gltfRuntime.textures[id];
  77427. if (texture.babylonTexture) {
  77428. onSuccess(texture.babylonTexture);
  77429. return;
  77430. }
  77431. var sampler = gltfRuntime.samplers[texture.sampler];
  77432. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  77433. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  77434. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  77435. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  77436. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77437. var blob = new Blob([buffer]);
  77438. var blobURL = URL.createObjectURL(blob);
  77439. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  77440. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  77441. if (sampler.wrapS !== undefined) {
  77442. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  77443. }
  77444. if (sampler.wrapT !== undefined) {
  77445. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  77446. }
  77447. newTexture.name = id;
  77448. texture.babylonTexture = newTexture;
  77449. onSuccess(newTexture);
  77450. };
  77451. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77452. var shader = gltfRuntime.shaders[id];
  77453. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  77454. var shaderString = atob(shader.uri.split(",")[1]);
  77455. onSuccess(shaderString);
  77456. }
  77457. else {
  77458. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  77459. if (request) {
  77460. onError(request.status + " " + request.statusText);
  77461. }
  77462. });
  77463. }
  77464. };
  77465. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77466. var material = gltfRuntime.materials[id];
  77467. if (!material.technique) {
  77468. if (onError) {
  77469. onError("No technique found.");
  77470. }
  77471. return;
  77472. }
  77473. var technique = gltfRuntime.techniques[material.technique];
  77474. if (!technique) {
  77475. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77476. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  77477. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77478. onSuccess(defaultMaterial);
  77479. return;
  77480. }
  77481. var program = gltfRuntime.programs[technique.program];
  77482. var states = technique.states;
  77483. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  77484. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  77485. var newVertexShader = "";
  77486. var newPixelShader = "";
  77487. var vertexTokenizer = new Tokenizer(vertexShader);
  77488. var pixelTokenizer = new Tokenizer(pixelShader);
  77489. var unTreatedUniforms = {};
  77490. var uniforms = [];
  77491. var attributes = [];
  77492. var samplers = [];
  77493. // Fill uniform, sampler2D and attributes
  77494. for (var unif in technique.uniforms) {
  77495. var uniform = technique.uniforms[unif];
  77496. var uniformParameter = technique.parameters[uniform];
  77497. unTreatedUniforms[unif] = uniformParameter;
  77498. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  77499. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77500. if (transformIndex !== -1) {
  77501. uniforms.push(babylonTransforms[transformIndex]);
  77502. delete unTreatedUniforms[unif];
  77503. }
  77504. else {
  77505. uniforms.push(unif);
  77506. }
  77507. }
  77508. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  77509. samplers.push(unif);
  77510. }
  77511. else {
  77512. uniforms.push(unif);
  77513. }
  77514. }
  77515. for (var attr in technique.attributes) {
  77516. var attribute = technique.attributes[attr];
  77517. var attributeParameter = technique.parameters[attribute];
  77518. if (attributeParameter.semantic) {
  77519. attributes.push(getAttribute(attributeParameter));
  77520. }
  77521. }
  77522. // Configure vertex shader
  77523. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  77524. var tokenType = vertexTokenizer.currentToken;
  77525. if (tokenType !== ETokenType.IDENTIFIER) {
  77526. newVertexShader += vertexTokenizer.currentString;
  77527. continue;
  77528. }
  77529. var foundAttribute = false;
  77530. for (var attr in technique.attributes) {
  77531. var attribute = technique.attributes[attr];
  77532. var attributeParameter = technique.parameters[attribute];
  77533. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  77534. newVertexShader += getAttribute(attributeParameter);
  77535. foundAttribute = true;
  77536. break;
  77537. }
  77538. }
  77539. if (foundAttribute) {
  77540. continue;
  77541. }
  77542. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  77543. }
  77544. // Configure pixel shader
  77545. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  77546. var tokenType = pixelTokenizer.currentToken;
  77547. if (tokenType !== ETokenType.IDENTIFIER) {
  77548. newPixelShader += pixelTokenizer.currentString;
  77549. continue;
  77550. }
  77551. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  77552. }
  77553. // Create shader material
  77554. var shaderPath = {
  77555. vertex: program.vertexShader + id,
  77556. fragment: program.fragmentShader + id
  77557. };
  77558. var options = {
  77559. attributes: attributes,
  77560. uniforms: uniforms,
  77561. samplers: samplers,
  77562. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  77563. };
  77564. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  77565. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  77566. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  77567. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  77568. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  77569. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77570. if (states && states.functions) {
  77571. var functions = states.functions;
  77572. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  77573. shaderMaterial.backFaceCulling = false;
  77574. }
  77575. var blendFunc = functions.blendFuncSeparate;
  77576. if (blendFunc) {
  77577. 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) {
  77578. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  77579. }
  77580. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77581. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77582. }
  77583. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77584. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  77585. }
  77586. 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) {
  77587. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  77588. }
  77589. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77590. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  77591. }
  77592. 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) {
  77593. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  77594. }
  77595. }
  77596. }
  77597. };
  77598. return GLTFLoaderBase;
  77599. }());
  77600. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  77601. /**
  77602. * glTF V1 Loader
  77603. */
  77604. var GLTFLoader = /** @class */ (function () {
  77605. function GLTFLoader() {
  77606. }
  77607. GLTFLoader.RegisterExtension = function (extension) {
  77608. if (GLTFLoader.Extensions[extension.name]) {
  77609. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77610. return;
  77611. }
  77612. GLTFLoader.Extensions[extension.name] = extension;
  77613. };
  77614. GLTFLoader.prototype.dispose = function () {
  77615. // do nothing
  77616. };
  77617. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77618. var _this = this;
  77619. scene.useRightHandedSystem = true;
  77620. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77621. gltfRuntime.importOnlyMeshes = true;
  77622. if (meshesNames === "") {
  77623. gltfRuntime.importMeshesNames = [];
  77624. }
  77625. else if (typeof meshesNames === "string") {
  77626. gltfRuntime.importMeshesNames = [meshesNames];
  77627. }
  77628. else if (meshesNames && !(meshesNames instanceof Array)) {
  77629. gltfRuntime.importMeshesNames = [meshesNames];
  77630. }
  77631. else {
  77632. gltfRuntime.importMeshesNames = [];
  77633. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77634. }
  77635. // Create nodes
  77636. _this._createNodes(gltfRuntime);
  77637. var meshes = new Array();
  77638. var skeletons = new Array();
  77639. // Fill arrays of meshes and skeletons
  77640. for (var nde in gltfRuntime.nodes) {
  77641. var node = gltfRuntime.nodes[nde];
  77642. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77643. meshes.push(node.babylonNode);
  77644. }
  77645. }
  77646. for (var skl in gltfRuntime.skins) {
  77647. var skin = gltfRuntime.skins[skl];
  77648. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77649. skeletons.push(skin.babylonSkeleton);
  77650. }
  77651. }
  77652. // Load buffers, shaders, materials, etc.
  77653. _this._loadBuffersAsync(gltfRuntime, function () {
  77654. _this._loadShadersAsync(gltfRuntime, function () {
  77655. importMaterials(gltfRuntime);
  77656. postLoad(gltfRuntime);
  77657. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77658. onSuccess(meshes, [], skeletons);
  77659. }
  77660. });
  77661. }, onProgress);
  77662. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77663. onSuccess(meshes, [], skeletons);
  77664. }
  77665. }, onError);
  77666. return true;
  77667. };
  77668. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77669. var _this = this;
  77670. scene.useRightHandedSystem = true;
  77671. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77672. // Load runtime extensios
  77673. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77674. // Create nodes
  77675. _this._createNodes(gltfRuntime);
  77676. // Load buffers, shaders, materials, etc.
  77677. _this._loadBuffersAsync(gltfRuntime, function () {
  77678. _this._loadShadersAsync(gltfRuntime, function () {
  77679. importMaterials(gltfRuntime);
  77680. postLoad(gltfRuntime);
  77681. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77682. onSuccess();
  77683. }
  77684. });
  77685. });
  77686. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77687. onSuccess();
  77688. }
  77689. }, onError);
  77690. }, onError);
  77691. };
  77692. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77693. var hasShaders = false;
  77694. var processShader = function (sha, shader) {
  77695. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77696. gltfRuntime.loadedShaderCount++;
  77697. if (shaderString) {
  77698. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77699. }
  77700. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77701. onload();
  77702. }
  77703. }, function () {
  77704. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77705. });
  77706. };
  77707. for (var sha in gltfRuntime.shaders) {
  77708. hasShaders = true;
  77709. var shader = gltfRuntime.shaders[sha];
  77710. if (shader) {
  77711. processShader.bind(this, sha, shader)();
  77712. }
  77713. else {
  77714. BABYLON.Tools.Error("No shader named: " + sha);
  77715. }
  77716. }
  77717. if (!hasShaders) {
  77718. onload();
  77719. }
  77720. };
  77721. ;
  77722. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77723. var hasBuffers = false;
  77724. var processBuffer = function (buf, buffer) {
  77725. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77726. gltfRuntime.loadedBufferCount++;
  77727. if (bufferView) {
  77728. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77729. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77730. }
  77731. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77732. }
  77733. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77734. onLoad();
  77735. }
  77736. }, function () {
  77737. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77738. });
  77739. };
  77740. for (var buf in gltfRuntime.buffers) {
  77741. hasBuffers = true;
  77742. var buffer = gltfRuntime.buffers[buf];
  77743. if (buffer) {
  77744. processBuffer.bind(this, buf, buffer)();
  77745. }
  77746. else {
  77747. BABYLON.Tools.Error("No buffer named: " + buf);
  77748. }
  77749. }
  77750. if (!hasBuffers) {
  77751. onLoad();
  77752. }
  77753. };
  77754. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77755. var currentScene = gltfRuntime.currentScene;
  77756. if (currentScene) {
  77757. // Only one scene even if multiple scenes are defined
  77758. for (var i = 0; i < currentScene.nodes.length; i++) {
  77759. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77760. }
  77761. }
  77762. else {
  77763. // Load all scenes
  77764. for (var thing in gltfRuntime.scenes) {
  77765. currentScene = gltfRuntime.scenes[thing];
  77766. for (var i = 0; i < currentScene.nodes.length; i++) {
  77767. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77768. }
  77769. }
  77770. }
  77771. };
  77772. GLTFLoader.Extensions = {};
  77773. return GLTFLoader;
  77774. }());
  77775. GLTF1.GLTFLoader = GLTFLoader;
  77776. ;
  77777. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77778. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77779. })(BABYLON || (BABYLON = {}));
  77780. //# sourceMappingURL=babylon.glTFLoader.js.map
  77781. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77782. var BABYLON;
  77783. (function (BABYLON) {
  77784. var GLTF1;
  77785. (function (GLTF1) {
  77786. /**
  77787. * Utils functions for GLTF
  77788. */
  77789. var GLTFUtils = /** @class */ (function () {
  77790. function GLTFUtils() {
  77791. }
  77792. /**
  77793. * Sets the given "parameter" matrix
  77794. * @param scene: the {BABYLON.Scene} object
  77795. * @param source: the source node where to pick the matrix
  77796. * @param parameter: the GLTF technique parameter
  77797. * @param uniformName: the name of the shader's uniform
  77798. * @param shaderMaterial: the shader material
  77799. */
  77800. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77801. var mat = null;
  77802. if (parameter.semantic === "MODEL") {
  77803. mat = source.getWorldMatrix();
  77804. }
  77805. else if (parameter.semantic === "PROJECTION") {
  77806. mat = scene.getProjectionMatrix();
  77807. }
  77808. else if (parameter.semantic === "VIEW") {
  77809. mat = scene.getViewMatrix();
  77810. }
  77811. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77812. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77813. }
  77814. else if (parameter.semantic === "MODELVIEW") {
  77815. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77816. }
  77817. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  77818. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  77819. }
  77820. else if (parameter.semantic === "MODELINVERSE") {
  77821. mat = source.getWorldMatrix().invert();
  77822. }
  77823. else if (parameter.semantic === "VIEWINVERSE") {
  77824. mat = scene.getViewMatrix().invert();
  77825. }
  77826. else if (parameter.semantic === "PROJECTIONINVERSE") {
  77827. mat = scene.getProjectionMatrix().invert();
  77828. }
  77829. else if (parameter.semantic === "MODELVIEWINVERSE") {
  77830. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  77831. }
  77832. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  77833. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  77834. }
  77835. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  77836. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  77837. }
  77838. else {
  77839. debugger;
  77840. }
  77841. if (mat) {
  77842. switch (parameter.type) {
  77843. case GLTF1.EParameterType.FLOAT_MAT2:
  77844. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  77845. break;
  77846. case GLTF1.EParameterType.FLOAT_MAT3:
  77847. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  77848. break;
  77849. case GLTF1.EParameterType.FLOAT_MAT4:
  77850. shaderMaterial.setMatrix(uniformName, mat);
  77851. break;
  77852. default: break;
  77853. }
  77854. }
  77855. };
  77856. /**
  77857. * Sets the given "parameter" matrix
  77858. * @param shaderMaterial: the shader material
  77859. * @param uniform: the name of the shader's uniform
  77860. * @param value: the value of the uniform
  77861. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  77862. */
  77863. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  77864. switch (type) {
  77865. case GLTF1.EParameterType.FLOAT:
  77866. shaderMaterial.setFloat(uniform, value);
  77867. return true;
  77868. case GLTF1.EParameterType.FLOAT_VEC2:
  77869. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  77870. return true;
  77871. case GLTF1.EParameterType.FLOAT_VEC3:
  77872. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  77873. return true;
  77874. case GLTF1.EParameterType.FLOAT_VEC4:
  77875. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  77876. return true;
  77877. default: return false;
  77878. }
  77879. };
  77880. /**
  77881. * If the uri is a base64 string
  77882. * @param uri: the uri to test
  77883. */
  77884. GLTFUtils.IsBase64 = function (uri) {
  77885. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  77886. };
  77887. /**
  77888. * Decode the base64 uri
  77889. * @param uri: the uri to decode
  77890. */
  77891. GLTFUtils.DecodeBase64 = function (uri) {
  77892. var decodedString = atob(uri.split(",")[1]);
  77893. var bufferLength = decodedString.length;
  77894. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  77895. for (var i = 0; i < bufferLength; i++) {
  77896. bufferView[i] = decodedString.charCodeAt(i);
  77897. }
  77898. return bufferView.buffer;
  77899. };
  77900. /**
  77901. * Returns the wrap mode of the texture
  77902. * @param mode: the mode value
  77903. */
  77904. GLTFUtils.GetWrapMode = function (mode) {
  77905. switch (mode) {
  77906. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  77907. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  77908. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77909. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77910. }
  77911. };
  77912. /**
  77913. * Returns the byte stride giving an accessor
  77914. * @param accessor: the GLTF accessor objet
  77915. */
  77916. GLTFUtils.GetByteStrideFromType = function (accessor) {
  77917. // Needs this function since "byteStride" isn't requiered in glTF format
  77918. var type = accessor.type;
  77919. switch (type) {
  77920. case "VEC2": return 2;
  77921. case "VEC3": return 3;
  77922. case "VEC4": return 4;
  77923. case "MAT2": return 4;
  77924. case "MAT3": return 9;
  77925. case "MAT4": return 16;
  77926. default: return 1;
  77927. }
  77928. };
  77929. /**
  77930. * Returns the texture filter mode giving a mode value
  77931. * @param mode: the filter mode value
  77932. */
  77933. GLTFUtils.GetTextureFilterMode = function (mode) {
  77934. switch (mode) {
  77935. case GLTF1.ETextureFilterType.LINEAR:
  77936. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  77937. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77938. case GLTF1.ETextureFilterType.NEAREST:
  77939. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  77940. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77941. }
  77942. };
  77943. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  77944. var byteOffset = bufferView.byteOffset + byteOffset;
  77945. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  77946. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  77947. throw new Error("Buffer access is out of range");
  77948. }
  77949. var buffer = loadedBufferView.buffer;
  77950. byteOffset += loadedBufferView.byteOffset;
  77951. switch (componentType) {
  77952. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  77953. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  77954. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  77955. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  77956. default: return new Float32Array(buffer, byteOffset, byteLength);
  77957. }
  77958. };
  77959. /**
  77960. * Returns a buffer from its accessor
  77961. * @param gltfRuntime: the GLTF runtime
  77962. * @param accessor: the GLTF accessor
  77963. */
  77964. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  77965. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  77966. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  77967. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  77968. };
  77969. /**
  77970. * Decodes a buffer view into a string
  77971. * @param view: the buffer view
  77972. */
  77973. GLTFUtils.DecodeBufferToText = function (view) {
  77974. var result = "";
  77975. var length = view.byteLength;
  77976. for (var i = 0; i < length; ++i) {
  77977. result += String.fromCharCode(view[i]);
  77978. }
  77979. return result;
  77980. };
  77981. /**
  77982. * Returns the default material of gltf. Related to
  77983. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  77984. * @param scene: the Babylon.js scene
  77985. */
  77986. GLTFUtils.GetDefaultMaterial = function (scene) {
  77987. if (!GLTFUtils._DefaultMaterial) {
  77988. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  77989. "precision highp float;",
  77990. "",
  77991. "uniform mat4 worldView;",
  77992. "uniform mat4 projection;",
  77993. "",
  77994. "attribute vec3 position;",
  77995. "",
  77996. "void main(void)",
  77997. "{",
  77998. " gl_Position = projection * worldView * vec4(position, 1.0);",
  77999. "}"
  78000. ].join("\n");
  78001. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  78002. "precision highp float;",
  78003. "",
  78004. "uniform vec4 u_emission;",
  78005. "",
  78006. "void main(void)",
  78007. "{",
  78008. " gl_FragColor = u_emission;",
  78009. "}"
  78010. ].join("\n");
  78011. var shaderPath = {
  78012. vertex: "GLTFDefaultMaterial",
  78013. fragment: "GLTFDefaultMaterial"
  78014. };
  78015. var options = {
  78016. attributes: ["position"],
  78017. uniforms: ["worldView", "projection", "u_emission"],
  78018. samplers: new Array(),
  78019. needAlphaBlending: false
  78020. };
  78021. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  78022. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  78023. }
  78024. return GLTFUtils._DefaultMaterial;
  78025. };
  78026. // The GLTF default material
  78027. GLTFUtils._DefaultMaterial = null;
  78028. return GLTFUtils;
  78029. }());
  78030. GLTF1.GLTFUtils = GLTFUtils;
  78031. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78032. })(BABYLON || (BABYLON = {}));
  78033. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  78034. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78035. var BABYLON;
  78036. (function (BABYLON) {
  78037. var GLTF1;
  78038. (function (GLTF1) {
  78039. var GLTFLoaderExtension = /** @class */ (function () {
  78040. function GLTFLoaderExtension(name) {
  78041. this._name = name;
  78042. }
  78043. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  78044. get: function () {
  78045. return this._name;
  78046. },
  78047. enumerable: true,
  78048. configurable: true
  78049. });
  78050. /**
  78051. * Defines an override for loading the runtime
  78052. * Return true to stop further extensions from loading the runtime
  78053. */
  78054. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78055. return false;
  78056. };
  78057. /**
  78058. * Defines an onverride for creating gltf runtime
  78059. * Return true to stop further extensions from creating the runtime
  78060. */
  78061. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78062. return false;
  78063. };
  78064. /**
  78065. * Defines an override for loading buffers
  78066. * Return true to stop further extensions from loading this buffer
  78067. */
  78068. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78069. return false;
  78070. };
  78071. /**
  78072. * Defines an override for loading texture buffers
  78073. * Return true to stop further extensions from loading this texture data
  78074. */
  78075. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78076. return false;
  78077. };
  78078. /**
  78079. * Defines an override for creating textures
  78080. * Return true to stop further extensions from loading this texture
  78081. */
  78082. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78083. return false;
  78084. };
  78085. /**
  78086. * Defines an override for loading shader strings
  78087. * Return true to stop further extensions from loading this shader data
  78088. */
  78089. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78090. return false;
  78091. };
  78092. /**
  78093. * Defines an override for loading materials
  78094. * Return true to stop further extensions from loading this material
  78095. */
  78096. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78097. return false;
  78098. };
  78099. // ---------
  78100. // Utilities
  78101. // ---------
  78102. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78103. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78104. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  78105. }, function () {
  78106. setTimeout(function () {
  78107. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78108. });
  78109. });
  78110. };
  78111. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78112. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78113. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  78114. }, function () {
  78115. setTimeout(function () {
  78116. onSuccess();
  78117. });
  78118. });
  78119. };
  78120. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78121. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78122. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78123. }, function () {
  78124. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78125. });
  78126. };
  78127. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  78128. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  78129. };
  78130. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78131. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78132. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78133. }, function () {
  78134. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78135. });
  78136. };
  78137. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78138. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78139. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78140. }, function () {
  78141. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78142. });
  78143. };
  78144. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78145. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78146. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78147. }, function () {
  78148. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78149. });
  78150. };
  78151. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78152. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78153. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78154. }, function () {
  78155. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78156. });
  78157. };
  78158. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  78159. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  78160. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  78161. if (func(loaderExtension)) {
  78162. return;
  78163. }
  78164. }
  78165. defaultFunc();
  78166. };
  78167. return GLTFLoaderExtension;
  78168. }());
  78169. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  78170. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78171. })(BABYLON || (BABYLON = {}));
  78172. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  78173. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78174. var BABYLON;
  78175. (function (BABYLON) {
  78176. var GLTF1;
  78177. (function (GLTF1) {
  78178. var BinaryExtensionBufferName = "binary_glTF";
  78179. ;
  78180. ;
  78181. var GLTFBinaryExtension = /** @class */ (function (_super) {
  78182. __extends(GLTFBinaryExtension, _super);
  78183. function GLTFBinaryExtension() {
  78184. return _super.call(this, "KHR_binary_glTF") || this;
  78185. }
  78186. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78187. var extensionsUsed = data.json.extensionsUsed;
  78188. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  78189. return false;
  78190. }
  78191. this._bin = data.bin;
  78192. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78193. return true;
  78194. };
  78195. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78196. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  78197. return false;
  78198. }
  78199. if (id !== BinaryExtensionBufferName) {
  78200. return false;
  78201. }
  78202. onSuccess(this._bin);
  78203. return true;
  78204. };
  78205. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78206. var texture = gltfRuntime.textures[id];
  78207. var source = gltfRuntime.images[texture.source];
  78208. if (!source.extensions || !(this.name in source.extensions)) {
  78209. return false;
  78210. }
  78211. var sourceExt = source.extensions[this.name];
  78212. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  78213. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78214. onSuccess(buffer);
  78215. return true;
  78216. };
  78217. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78218. var shader = gltfRuntime.shaders[id];
  78219. if (!shader.extensions || !(this.name in shader.extensions)) {
  78220. return false;
  78221. }
  78222. var binaryExtensionShader = shader.extensions[this.name];
  78223. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  78224. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78225. setTimeout(function () {
  78226. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  78227. onSuccess(shaderString);
  78228. });
  78229. return true;
  78230. };
  78231. return GLTFBinaryExtension;
  78232. }(GLTF1.GLTFLoaderExtension));
  78233. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  78234. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  78235. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78236. })(BABYLON || (BABYLON = {}));
  78237. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  78238. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78239. var BABYLON;
  78240. (function (BABYLON) {
  78241. var GLTF1;
  78242. (function (GLTF1) {
  78243. ;
  78244. ;
  78245. ;
  78246. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  78247. __extends(GLTFMaterialsCommonExtension, _super);
  78248. function GLTFMaterialsCommonExtension() {
  78249. return _super.call(this, "KHR_materials_common") || this;
  78250. }
  78251. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78252. if (!gltfRuntime.extensions)
  78253. return false;
  78254. var extension = gltfRuntime.extensions[this.name];
  78255. if (!extension)
  78256. return false;
  78257. // Create lights
  78258. var lights = extension.lights;
  78259. if (lights) {
  78260. for (var thing in lights) {
  78261. var light = lights[thing];
  78262. switch (light.type) {
  78263. case "ambient":
  78264. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  78265. var ambient = light.ambient;
  78266. if (ambient) {
  78267. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  78268. }
  78269. break;
  78270. case "point":
  78271. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  78272. var point = light.point;
  78273. if (point) {
  78274. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  78275. }
  78276. break;
  78277. case "directional":
  78278. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  78279. var directional = light.directional;
  78280. if (directional) {
  78281. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  78282. }
  78283. break;
  78284. case "spot":
  78285. var spot = light.spot;
  78286. if (spot) {
  78287. 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);
  78288. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  78289. }
  78290. break;
  78291. default:
  78292. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  78293. break;
  78294. }
  78295. }
  78296. }
  78297. return false;
  78298. };
  78299. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78300. var material = gltfRuntime.materials[id];
  78301. if (!material || !material.extensions)
  78302. return false;
  78303. var extension = material.extensions[this.name];
  78304. if (!extension)
  78305. return false;
  78306. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  78307. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78308. if (extension.technique === "CONSTANT") {
  78309. standardMaterial.disableLighting = true;
  78310. }
  78311. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  78312. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  78313. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  78314. // Ambient
  78315. if (typeof extension.values.ambient === "string") {
  78316. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  78317. }
  78318. else {
  78319. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  78320. }
  78321. // Diffuse
  78322. if (typeof extension.values.diffuse === "string") {
  78323. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  78324. }
  78325. else {
  78326. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  78327. }
  78328. // Emission
  78329. if (typeof extension.values.emission === "string") {
  78330. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  78331. }
  78332. else {
  78333. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  78334. }
  78335. // Specular
  78336. if (typeof extension.values.specular === "string") {
  78337. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  78338. }
  78339. else {
  78340. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  78341. }
  78342. return true;
  78343. };
  78344. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  78345. // Create buffer from texture url
  78346. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  78347. // Create texture from buffer
  78348. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  78349. }, onError);
  78350. };
  78351. return GLTFMaterialsCommonExtension;
  78352. }(GLTF1.GLTFLoaderExtension));
  78353. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  78354. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  78355. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78356. })(BABYLON || (BABYLON = {}));
  78357. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  78358. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78359. var BABYLON;
  78360. (function (BABYLON) {
  78361. var GLTF2;
  78362. (function (GLTF2) {
  78363. /**
  78364. * Enums
  78365. */
  78366. var EComponentType;
  78367. (function (EComponentType) {
  78368. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78369. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78370. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78371. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78372. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78373. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78374. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  78375. var EMeshPrimitiveMode;
  78376. (function (EMeshPrimitiveMode) {
  78377. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  78378. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  78379. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  78380. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  78381. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  78382. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  78383. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  78384. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  78385. var ETextureMagFilter;
  78386. (function (ETextureMagFilter) {
  78387. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  78388. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  78389. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  78390. var ETextureMinFilter;
  78391. (function (ETextureMinFilter) {
  78392. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  78393. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  78394. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78395. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78396. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78397. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78398. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  78399. var ETextureWrapMode;
  78400. (function (ETextureWrapMode) {
  78401. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78402. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78403. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78404. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  78405. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78406. })(BABYLON || (BABYLON = {}));
  78407. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  78408. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78409. var BABYLON;
  78410. (function (BABYLON) {
  78411. var GLTF2;
  78412. (function (GLTF2) {
  78413. var GLTFLoaderTracker = /** @class */ (function () {
  78414. function GLTFLoaderTracker(onComplete) {
  78415. this._pendingCount = 0;
  78416. this._callback = onComplete;
  78417. }
  78418. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  78419. this._pendingCount++;
  78420. };
  78421. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  78422. if (--this._pendingCount === 0) {
  78423. this._callback();
  78424. }
  78425. };
  78426. return GLTFLoaderTracker;
  78427. }());
  78428. var GLTFLoader = /** @class */ (function () {
  78429. function GLTFLoader(parent) {
  78430. this._disposed = false;
  78431. this._renderReady = false;
  78432. this._requests = new Array();
  78433. this._renderReadyObservable = new BABYLON.Observable();
  78434. // Count of pending work that needs to complete before the asset is rendered.
  78435. this._renderPendingCount = 0;
  78436. // Count of pending work that needs to complete before the loader is disposed.
  78437. this._loaderPendingCount = 0;
  78438. this._loaderTrackers = new Array();
  78439. this._parent = parent;
  78440. }
  78441. GLTFLoader.RegisterExtension = function (extension) {
  78442. if (GLTFLoader.Extensions[extension.name]) {
  78443. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  78444. return;
  78445. }
  78446. GLTFLoader.Extensions[extension.name] = extension;
  78447. // Keep the order of registration so that extensions registered first are called first.
  78448. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  78449. };
  78450. GLTFLoader.prototype.dispose = function () {
  78451. if (this._disposed) {
  78452. return;
  78453. }
  78454. this._disposed = true;
  78455. // Abort requests that are not complete
  78456. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  78457. var request = _a[_i];
  78458. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  78459. request.abort();
  78460. }
  78461. }
  78462. // Revoke object urls created during load
  78463. if (this._gltf.textures) {
  78464. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  78465. var texture = _c[_b];
  78466. if (texture.url) {
  78467. URL.revokeObjectURL(texture.url);
  78468. }
  78469. }
  78470. }
  78471. };
  78472. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78473. var _this = this;
  78474. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  78475. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  78476. }, onProgress, onError);
  78477. };
  78478. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78479. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  78480. };
  78481. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78482. var _this = this;
  78483. this._tryCatchOnError(function () {
  78484. _this._loadData(data);
  78485. _this._babylonScene = scene;
  78486. _this._rootUrl = rootUrl;
  78487. _this._successCallback = onSuccess;
  78488. _this._progressCallback = onProgress;
  78489. _this._errorCallback = onError;
  78490. _this._addPendingData(_this);
  78491. _this._loadDefaultScene(nodeNames);
  78492. _this._loadAnimations();
  78493. _this._removePendingData(_this);
  78494. });
  78495. };
  78496. GLTFLoader.prototype._onProgress = function (event) {
  78497. if (this._progressCallback) {
  78498. this._progressCallback(event);
  78499. }
  78500. };
  78501. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  78502. if (this._renderReady) {
  78503. func();
  78504. }
  78505. else {
  78506. this._renderReadyObservable.add(func);
  78507. }
  78508. };
  78509. GLTFLoader.prototype._onRenderReady = function () {
  78510. this._rootNode.babylonMesh.setEnabled(true);
  78511. this._startAnimations();
  78512. this._successCallback();
  78513. this._renderReadyObservable.notifyObservers(this);
  78514. };
  78515. GLTFLoader.prototype._onComplete = function () {
  78516. if (this._parent.onComplete) {
  78517. this._parent.onComplete();
  78518. }
  78519. this.dispose();
  78520. };
  78521. GLTFLoader.prototype._loadData = function (data) {
  78522. this._gltf = data.json;
  78523. // Assign the index of each object for convinience.
  78524. GLTFLoader._AssignIndices(this._gltf.accessors);
  78525. GLTFLoader._AssignIndices(this._gltf.animations);
  78526. GLTFLoader._AssignIndices(this._gltf.buffers);
  78527. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  78528. GLTFLoader._AssignIndices(this._gltf.images);
  78529. GLTFLoader._AssignIndices(this._gltf.materials);
  78530. GLTFLoader._AssignIndices(this._gltf.meshes);
  78531. GLTFLoader._AssignIndices(this._gltf.nodes);
  78532. GLTFLoader._AssignIndices(this._gltf.scenes);
  78533. GLTFLoader._AssignIndices(this._gltf.skins);
  78534. GLTFLoader._AssignIndices(this._gltf.textures);
  78535. if (data.bin) {
  78536. var buffers = this._gltf.buffers;
  78537. if (buffers && buffers[0] && !buffers[0].uri) {
  78538. var binaryBuffer = buffers[0];
  78539. if (binaryBuffer.byteLength != data.bin.byteLength) {
  78540. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  78541. }
  78542. binaryBuffer.loadedData = data.bin;
  78543. }
  78544. else {
  78545. BABYLON.Tools.Warn("Unexpected BIN chunk");
  78546. }
  78547. }
  78548. };
  78549. GLTFLoader.prototype._getMeshes = function () {
  78550. var meshes = new Array();
  78551. // Root mesh is always first.
  78552. meshes.push(this._rootNode.babylonMesh);
  78553. var nodes = this._gltf.nodes;
  78554. if (nodes) {
  78555. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  78556. var node = nodes_1[_i];
  78557. if (node.babylonMesh) {
  78558. meshes.push(node.babylonMesh);
  78559. }
  78560. }
  78561. }
  78562. return meshes;
  78563. };
  78564. GLTFLoader.prototype._getSkeletons = function () {
  78565. var skeletons = new Array();
  78566. var skins = this._gltf.skins;
  78567. if (skins) {
  78568. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  78569. var skin = skins_1[_i];
  78570. if (skin.babylonSkeleton) {
  78571. skeletons.push(skin.babylonSkeleton);
  78572. }
  78573. }
  78574. }
  78575. return skeletons;
  78576. };
  78577. GLTFLoader.prototype._getAnimationTargets = function () {
  78578. var targets = new Array();
  78579. var animations = this._gltf.animations;
  78580. if (animations) {
  78581. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78582. var animation = animations_1[_i];
  78583. targets.push.apply(targets, animation.targets);
  78584. }
  78585. }
  78586. return targets;
  78587. };
  78588. GLTFLoader.prototype._startAnimations = function () {
  78589. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78590. var target = _a[_i];
  78591. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78592. }
  78593. };
  78594. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78595. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  78596. if (!scene) {
  78597. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78598. }
  78599. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78600. };
  78601. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78602. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78603. switch (this._parent.coordinateSystemMode) {
  78604. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  78605. if (!this._babylonScene.useRightHandedSystem) {
  78606. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78607. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78608. }
  78609. break;
  78610. }
  78611. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  78612. // do nothing
  78613. break;
  78614. }
  78615. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  78616. this._babylonScene.useRightHandedSystem = true;
  78617. break;
  78618. }
  78619. default: {
  78620. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  78621. return;
  78622. }
  78623. }
  78624. var nodeIndices = scene.nodes;
  78625. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78626. node.parent = parentNode;
  78627. return true;
  78628. }, this._rootNode);
  78629. if (nodeNames) {
  78630. if (!(nodeNames instanceof Array)) {
  78631. nodeNames = [nodeNames];
  78632. }
  78633. var filteredNodeIndices_1 = new Array();
  78634. this._traverseNodes(context, nodeIndices, function (node) {
  78635. if (nodeNames.indexOf(node.name) !== -1) {
  78636. filteredNodeIndices_1.push(node.index);
  78637. return false;
  78638. }
  78639. return true;
  78640. }, this._rootNode);
  78641. nodeIndices = filteredNodeIndices_1;
  78642. }
  78643. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78644. var index = nodeIndices_1[_i];
  78645. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78646. if (!node) {
  78647. throw new Error(context + ": Failed to find node " + index);
  78648. }
  78649. this._loadNode("#/nodes/" + index, node);
  78650. }
  78651. // Disable the root mesh until the asset is ready to render.
  78652. this._rootNode.babylonMesh.setEnabled(false);
  78653. };
  78654. GLTFLoader.prototype._loadNode = function (context, node) {
  78655. node.babylonBones = {};
  78656. node.babylonAnimationTargets = [];
  78657. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78658. return;
  78659. }
  78660. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78661. this._loadTransform(node);
  78662. if (node.mesh != null) {
  78663. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  78664. if (!mesh) {
  78665. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78666. }
  78667. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78668. }
  78669. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  78670. node.babylonAnimationTargets.push(node.babylonMesh);
  78671. if (node.skin != null) {
  78672. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  78673. if (!skin) {
  78674. throw new Error(context + ": Failed to find skin " + node.skin);
  78675. }
  78676. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78677. }
  78678. if (node.camera != null) {
  78679. // TODO: handle cameras
  78680. }
  78681. if (node.children) {
  78682. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78683. var index = _a[_i];
  78684. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78685. if (!childNode) {
  78686. throw new Error(context + ": Failed to find child node " + index);
  78687. }
  78688. this._loadNode("#/nodes/" + index, childNode);
  78689. }
  78690. }
  78691. };
  78692. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78693. var _this = this;
  78694. var primitives = mesh.primitives;
  78695. if (!primitives || primitives.length === 0) {
  78696. throw new Error(context + ": Primitives are missing");
  78697. }
  78698. this._createMorphTargets(context, node, mesh);
  78699. this._loadAllVertexDataAsync(context, mesh, function () {
  78700. _this._loadMorphTargets(context, node, mesh);
  78701. var vertexData = new BABYLON.VertexData();
  78702. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78703. var primitive = primitives_1[_i];
  78704. vertexData.merge(primitive.vertexData);
  78705. }
  78706. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78707. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78708. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78709. node.babylonMesh.subMeshes = [];
  78710. var verticesStart = 0;
  78711. var indicesStart = 0;
  78712. for (var index = 0; index < primitives.length; index++) {
  78713. var vertexData_1 = primitives[index].vertexData;
  78714. var verticesCount = vertexData_1.positions.length;
  78715. var indicesCount = vertexData_1.indices.length;
  78716. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78717. verticesStart += verticesCount;
  78718. indicesStart += indicesCount;
  78719. }
  78720. ;
  78721. });
  78722. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78723. node.babylonMesh.material = multiMaterial;
  78724. var subMaterials = multiMaterial.subMaterials;
  78725. var _loop_1 = function (index) {
  78726. var primitive = primitives[index];
  78727. if (primitive.material == null) {
  78728. subMaterials[index] = this_1._getDefaultMaterial();
  78729. }
  78730. else {
  78731. var material_1 = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  78732. if (!material_1) {
  78733. throw new Error(context + ": Failed to find material " + primitive.material);
  78734. }
  78735. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78736. if (isNew && _this._parent.onMaterialLoaded) {
  78737. _this._parent.onMaterialLoaded(babylonMaterial);
  78738. }
  78739. if (_this._parent.onBeforeMaterialReadyAsync) {
  78740. _this._addLoaderPendingData(material_1);
  78741. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78742. _this._tryCatchOnError(function () {
  78743. subMaterials[index] = babylonMaterial;
  78744. _this._removeLoaderPendingData(material_1);
  78745. });
  78746. });
  78747. }
  78748. else {
  78749. subMaterials[index] = babylonMaterial;
  78750. }
  78751. });
  78752. }
  78753. };
  78754. var this_1 = this;
  78755. for (var index = 0; index < primitives.length; index++) {
  78756. _loop_1(index);
  78757. }
  78758. ;
  78759. };
  78760. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78761. var primitives = mesh.primitives;
  78762. var numRemainingPrimitives = primitives.length;
  78763. var _loop_2 = function (index) {
  78764. var primitive = primitives[index];
  78765. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78766. primitive.vertexData = vertexData;
  78767. if (--numRemainingPrimitives === 0) {
  78768. onSuccess();
  78769. }
  78770. });
  78771. };
  78772. var this_2 = this;
  78773. for (var index = 0; index < primitives.length; index++) {
  78774. _loop_2(index);
  78775. }
  78776. };
  78777. /**
  78778. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  78779. * @param {ArrayBufferView} data
  78780. * @param {IGLTFAccessor} accessor
  78781. */
  78782. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  78783. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  78784. return data;
  78785. }
  78786. var buffer = data;
  78787. var factor = 1;
  78788. switch (accessor.componentType) {
  78789. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78790. factor = 1 / 255;
  78791. break;
  78792. }
  78793. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78794. factor = 1 / 65535;
  78795. break;
  78796. }
  78797. default: {
  78798. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78799. }
  78800. }
  78801. var result = new Float32Array(accessor.count * 2);
  78802. for (var i = 0; i < result.length; ++i) {
  78803. result[i] = buffer[i] * factor;
  78804. }
  78805. return result;
  78806. };
  78807. /**
  78808. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  78809. * @param {ArrayBufferView} data
  78810. * @param {IGLTFAccessor} accessor
  78811. */
  78812. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  78813. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  78814. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  78815. return data;
  78816. }
  78817. var buffer = data;
  78818. var factor = 1;
  78819. switch (accessor.componentType) {
  78820. case GLTF2.EComponentType.FLOAT: {
  78821. factor = 1;
  78822. break;
  78823. }
  78824. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78825. factor = 1 / 255;
  78826. break;
  78827. }
  78828. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78829. factor = 1 / 65535;
  78830. break;
  78831. }
  78832. default: {
  78833. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78834. }
  78835. }
  78836. var result = new Float32Array(accessor.count * 4);
  78837. if (colorComponentCount === 4) {
  78838. for (var i = 0; i < result.length; ++i) {
  78839. result[i] = buffer[i] * factor;
  78840. }
  78841. }
  78842. else {
  78843. var offset = 0;
  78844. for (var i = 0; i < result.length; ++i) {
  78845. if ((i + 1) % 4 === 0) {
  78846. result[i] = 1;
  78847. }
  78848. else {
  78849. result[i] = buffer[offset++] * factor;
  78850. }
  78851. }
  78852. }
  78853. return result;
  78854. };
  78855. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  78856. var _this = this;
  78857. var attributes = primitive.attributes;
  78858. if (!attributes) {
  78859. throw new Error(context + ": Attributes are missing");
  78860. }
  78861. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  78862. // TODO: handle other primitive modes
  78863. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  78864. }
  78865. var vertexData = new BABYLON.VertexData();
  78866. var numRemainingAttributes = Object.keys(attributes).length;
  78867. var _loop_3 = function (attribute) {
  78868. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  78869. if (!accessor) {
  78870. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78871. }
  78872. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78873. switch (attribute) {
  78874. case "POSITION": {
  78875. vertexData.positions = data;
  78876. break;
  78877. }
  78878. case "NORMAL": {
  78879. vertexData.normals = data;
  78880. break;
  78881. }
  78882. case "TANGENT": {
  78883. vertexData.tangents = data;
  78884. break;
  78885. }
  78886. case "TEXCOORD_0": {
  78887. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78888. break;
  78889. }
  78890. case "TEXCOORD_1": {
  78891. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78892. break;
  78893. }
  78894. case "JOINTS_0": {
  78895. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  78896. break;
  78897. }
  78898. case "WEIGHTS_0": {
  78899. //TODO: need to add support for normalized weights.
  78900. vertexData.matricesWeights = data;
  78901. break;
  78902. }
  78903. case "COLOR_0": {
  78904. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  78905. break;
  78906. }
  78907. default: {
  78908. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78909. break;
  78910. }
  78911. }
  78912. if (--numRemainingAttributes === 0) {
  78913. if (primitive.indices == null) {
  78914. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  78915. for (var i = 0; i < vertexData.indices.length; i++) {
  78916. vertexData.indices[i] = i;
  78917. }
  78918. onSuccess(vertexData);
  78919. }
  78920. else {
  78921. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  78922. if (!indicesAccessor) {
  78923. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  78924. }
  78925. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  78926. vertexData.indices = data;
  78927. onSuccess(vertexData);
  78928. });
  78929. }
  78930. }
  78931. });
  78932. };
  78933. var this_3 = this;
  78934. for (var attribute in attributes) {
  78935. _loop_3(attribute);
  78936. }
  78937. };
  78938. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  78939. var primitives = mesh.primitives;
  78940. var targets = primitives[0].targets;
  78941. if (!targets) {
  78942. return;
  78943. }
  78944. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  78945. var primitive = primitives_2[_i];
  78946. if (!primitive.targets || primitive.targets.length != targets.length) {
  78947. throw new Error(context + ": All primitives are required to list the same number of targets");
  78948. }
  78949. }
  78950. var morphTargetManager = new BABYLON.MorphTargetManager();
  78951. node.babylonMesh.morphTargetManager = morphTargetManager;
  78952. for (var index = 0; index < targets.length; index++) {
  78953. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  78954. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  78955. }
  78956. };
  78957. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  78958. var morphTargetManager = node.babylonMesh.morphTargetManager;
  78959. if (!morphTargetManager) {
  78960. return;
  78961. }
  78962. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  78963. var numTargets = morphTargetManager.numTargets;
  78964. for (var index = 0; index < numTargets; index++) {
  78965. var vertexData = new BABYLON.VertexData();
  78966. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78967. var primitive = _a[_i];
  78968. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  78969. }
  78970. if (!vertexData.positions) {
  78971. throw new Error(context + ": Positions are missing");
  78972. }
  78973. var target = morphTargetManager.getTarget(index);
  78974. target.setPositions(vertexData.positions);
  78975. target.setNormals(vertexData.normals);
  78976. target.setTangents(vertexData.tangents);
  78977. }
  78978. });
  78979. };
  78980. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  78981. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  78982. var _loop_4 = function (primitive) {
  78983. var targets = primitive.targets;
  78984. primitive.targetsVertexData = new Array(targets.length);
  78985. var _loop_5 = function (index) {
  78986. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  78987. primitive.targetsVertexData[index] = vertexData;
  78988. if (--numRemainingTargets === 0) {
  78989. onSuccess();
  78990. }
  78991. });
  78992. };
  78993. for (var index = 0; index < targets.length; index++) {
  78994. _loop_5(index);
  78995. }
  78996. };
  78997. var this_4 = this;
  78998. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78999. var primitive = _a[_i];
  79000. _loop_4(primitive);
  79001. }
  79002. };
  79003. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  79004. var targetVertexData = new BABYLON.VertexData();
  79005. var numRemainingAttributes = Object.keys(attributes).length;
  79006. var _loop_6 = function (attribute) {
  79007. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  79008. if (!accessor) {
  79009. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  79010. }
  79011. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79012. // glTF stores morph target information as deltas while babylon.js expects the final data.
  79013. // As a result we have to add the original data to the delta to calculate the final data.
  79014. var values = data;
  79015. switch (attribute) {
  79016. case "POSITION": {
  79017. for (var i = 0; i < values.length; i++) {
  79018. values[i] += vertexData.positions[i];
  79019. }
  79020. targetVertexData.positions = values;
  79021. break;
  79022. }
  79023. case "NORMAL": {
  79024. for (var i = 0; i < values.length; i++) {
  79025. values[i] += vertexData.normals[i];
  79026. }
  79027. targetVertexData.normals = values;
  79028. break;
  79029. }
  79030. case "TANGENT": {
  79031. // Tangent data for morph targets is stored as xyz delta.
  79032. // The vertexData.tangent is stored as xyzw.
  79033. // So we need to skip every fourth vertexData.tangent.
  79034. for (var i = 0, j = 0; i < values.length; i++, j++) {
  79035. values[i] += vertexData.tangents[j];
  79036. if ((i + 1) % 3 == 0) {
  79037. j++;
  79038. }
  79039. }
  79040. targetVertexData.tangents = values;
  79041. break;
  79042. }
  79043. default: {
  79044. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  79045. break;
  79046. }
  79047. }
  79048. if (--numRemainingAttributes === 0) {
  79049. onSuccess(targetVertexData);
  79050. }
  79051. });
  79052. };
  79053. var this_5 = this;
  79054. for (var attribute in attributes) {
  79055. _loop_6(attribute);
  79056. }
  79057. };
  79058. GLTFLoader.prototype._loadTransform = function (node) {
  79059. var position = BABYLON.Vector3.Zero();
  79060. var rotation = BABYLON.Quaternion.Identity();
  79061. var scaling = BABYLON.Vector3.One();
  79062. if (node.matrix) {
  79063. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  79064. matrix.decompose(scaling, rotation, position);
  79065. }
  79066. else {
  79067. if (node.translation)
  79068. position = BABYLON.Vector3.FromArray(node.translation);
  79069. if (node.rotation)
  79070. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  79071. if (node.scale)
  79072. scaling = BABYLON.Vector3.FromArray(node.scale);
  79073. }
  79074. node.babylonMesh.position = position;
  79075. node.babylonMesh.rotationQuaternion = rotation;
  79076. node.babylonMesh.scaling = scaling;
  79077. };
  79078. GLTFLoader.prototype._loadSkin = function (context, skin) {
  79079. var _this = this;
  79080. var skeletonId = "skeleton" + skin.index;
  79081. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  79082. if (skin.inverseBindMatrices == null) {
  79083. this._loadBones(context, skin, null);
  79084. }
  79085. else {
  79086. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  79087. if (!accessor) {
  79088. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  79089. }
  79090. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79091. _this._loadBones(context, skin, data);
  79092. });
  79093. }
  79094. return skin.babylonSkeleton;
  79095. };
  79096. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  79097. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  79098. node.babylonBones[skin.index] = babylonBone;
  79099. node.babylonAnimationTargets.push(babylonBone);
  79100. return babylonBone;
  79101. };
  79102. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  79103. var babylonBones = {};
  79104. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  79105. var index = _a[_i];
  79106. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79107. if (!node) {
  79108. throw new Error(context + ": Failed to find joint " + index);
  79109. }
  79110. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  79111. }
  79112. };
  79113. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  79114. var babylonBone = babylonBones[node.index];
  79115. if (babylonBone) {
  79116. return babylonBone;
  79117. }
  79118. var boneIndex = skin.joints.indexOf(node.index);
  79119. var baseMatrix = BABYLON.Matrix.Identity();
  79120. if (inverseBindMatrixData && boneIndex !== -1) {
  79121. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  79122. baseMatrix.invertToRef(baseMatrix);
  79123. }
  79124. var babylonParentBone = null;
  79125. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  79126. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  79127. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  79128. }
  79129. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  79130. babylonBones[node.index] = babylonBone;
  79131. return babylonBone;
  79132. };
  79133. GLTFLoader.prototype._getNodeMatrix = function (node) {
  79134. return node.matrix ?
  79135. BABYLON.Matrix.FromArray(node.matrix) :
  79136. 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());
  79137. };
  79138. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  79139. if (parentNode === void 0) { parentNode = null; }
  79140. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  79141. var index = indices_1[_i];
  79142. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79143. if (!node) {
  79144. throw new Error(context + ": Failed to find node " + index);
  79145. }
  79146. this._traverseNode(context, node, action, parentNode);
  79147. }
  79148. };
  79149. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  79150. if (parentNode === void 0) { parentNode = null; }
  79151. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  79152. return;
  79153. }
  79154. if (!action(node, parentNode)) {
  79155. return;
  79156. }
  79157. if (node.children) {
  79158. this._traverseNodes(context, node.children, action, node);
  79159. }
  79160. };
  79161. GLTFLoader.prototype._loadAnimations = function () {
  79162. var animations = this._gltf.animations;
  79163. if (!animations) {
  79164. return;
  79165. }
  79166. for (var index = 0; index < animations.length; index++) {
  79167. var animation = animations[index];
  79168. this._loadAnimation("#/animations/" + index, animation);
  79169. }
  79170. };
  79171. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  79172. animation.targets = [];
  79173. for (var index = 0; index < animation.channels.length; index++) {
  79174. var channel = GLTFLoader._GetProperty(animation.channels, index);
  79175. if (!channel) {
  79176. throw new Error(context + ": Failed to find channel " + index);
  79177. }
  79178. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  79179. if (!sampler) {
  79180. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  79181. }
  79182. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  79183. }
  79184. };
  79185. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  79186. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  79187. if (!targetNode) {
  79188. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  79189. }
  79190. var targetPath;
  79191. var animationType;
  79192. switch (channel.target.path) {
  79193. case "translation": {
  79194. targetPath = "position";
  79195. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79196. break;
  79197. }
  79198. case "rotation": {
  79199. targetPath = "rotationQuaternion";
  79200. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  79201. break;
  79202. }
  79203. case "scale": {
  79204. targetPath = "scaling";
  79205. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79206. break;
  79207. }
  79208. case "weights": {
  79209. targetPath = "influence";
  79210. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  79211. break;
  79212. }
  79213. default: {
  79214. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  79215. }
  79216. }
  79217. var inputData;
  79218. var outputData;
  79219. var checkSuccess = function () {
  79220. if (!inputData || !outputData) {
  79221. return;
  79222. }
  79223. var outputBufferOffset = 0;
  79224. var getNextOutputValue;
  79225. switch (targetPath) {
  79226. case "position": {
  79227. getNextOutputValue = function () {
  79228. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79229. outputBufferOffset += 3;
  79230. return value;
  79231. };
  79232. break;
  79233. }
  79234. case "rotationQuaternion": {
  79235. getNextOutputValue = function () {
  79236. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  79237. outputBufferOffset += 4;
  79238. return value;
  79239. };
  79240. break;
  79241. }
  79242. case "scaling": {
  79243. getNextOutputValue = function () {
  79244. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79245. outputBufferOffset += 3;
  79246. return value;
  79247. };
  79248. break;
  79249. }
  79250. case "influence": {
  79251. getNextOutputValue = function () {
  79252. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  79253. var value = new Array(numTargets);
  79254. for (var i = 0; i < numTargets; i++) {
  79255. value[i] = outputData[outputBufferOffset++];
  79256. }
  79257. return value;
  79258. };
  79259. break;
  79260. }
  79261. }
  79262. var getNextKey;
  79263. switch (sampler.interpolation) {
  79264. case "LINEAR": {
  79265. getNextKey = function (frameIndex) { return ({
  79266. frame: inputData[frameIndex],
  79267. value: getNextOutputValue()
  79268. }); };
  79269. break;
  79270. }
  79271. case "CUBICSPLINE": {
  79272. getNextKey = function (frameIndex) { return ({
  79273. frame: inputData[frameIndex],
  79274. inTangent: getNextOutputValue(),
  79275. value: getNextOutputValue(),
  79276. outTangent: getNextOutputValue()
  79277. }); };
  79278. break;
  79279. }
  79280. default: {
  79281. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  79282. }
  79283. }
  79284. ;
  79285. var keys = new Array(inputData.length);
  79286. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  79287. keys[frameIndex] = getNextKey(frameIndex);
  79288. }
  79289. if (targetPath === "influence") {
  79290. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  79291. var _loop_7 = function (targetIndex) {
  79292. var morphTarget = morphTargetManager.getTarget(targetIndex);
  79293. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  79294. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79295. babylonAnimation.setKeys(keys.map(function (key) { return ({
  79296. frame: key.frame,
  79297. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  79298. value: key.value[targetIndex],
  79299. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  79300. }); }));
  79301. morphTarget.animations.push(babylonAnimation);
  79302. animation.targets.push(morphTarget);
  79303. };
  79304. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  79305. _loop_7(targetIndex);
  79306. }
  79307. }
  79308. else {
  79309. var animationName = animation.name || "anim" + animation.index;
  79310. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79311. babylonAnimation.setKeys(keys);
  79312. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  79313. var target = _a[_i];
  79314. target.animations.push(babylonAnimation.clone());
  79315. animation.targets.push(target);
  79316. }
  79317. }
  79318. };
  79319. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  79320. if (!inputAccessor) {
  79321. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  79322. }
  79323. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  79324. inputData = data;
  79325. checkSuccess();
  79326. });
  79327. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  79328. if (!outputAccessor) {
  79329. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  79330. }
  79331. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  79332. outputData = data;
  79333. checkSuccess();
  79334. });
  79335. };
  79336. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  79337. var _this = this;
  79338. this._addPendingData(buffer);
  79339. if (buffer.loadedData) {
  79340. onSuccess(buffer.loadedData);
  79341. this._removePendingData(buffer);
  79342. }
  79343. else if (buffer.loadedObservable) {
  79344. buffer.loadedObservable.add(function (buffer) {
  79345. onSuccess(buffer.loadedData);
  79346. _this._removePendingData(buffer);
  79347. });
  79348. }
  79349. else {
  79350. if (!buffer.uri) {
  79351. throw new Error(context + ": Uri is missing");
  79352. }
  79353. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  79354. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  79355. buffer.loadedData = new Uint8Array(data);
  79356. onSuccess(buffer.loadedData);
  79357. this._removePendingData(buffer);
  79358. }
  79359. else {
  79360. buffer.loadedObservable = new BABYLON.Observable();
  79361. buffer.loadedObservable.add(function (buffer) {
  79362. onSuccess(buffer.loadedData);
  79363. _this._removePendingData(buffer);
  79364. });
  79365. this._loadUri(context, buffer.uri, function (data) {
  79366. buffer.loadedData = data;
  79367. buffer.loadedObservable.notifyObservers(buffer);
  79368. buffer.loadedObservable = undefined;
  79369. });
  79370. }
  79371. }
  79372. };
  79373. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  79374. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  79375. if (!buffer) {
  79376. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  79377. }
  79378. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  79379. var data;
  79380. try {
  79381. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  79382. }
  79383. catch (e) {
  79384. throw new Error(context + ": " + e.message);
  79385. }
  79386. onSuccess(data);
  79387. });
  79388. };
  79389. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  79390. var _this = this;
  79391. if (accessor.sparse) {
  79392. throw new Error(context + ": Sparse accessors are not currently supported");
  79393. }
  79394. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  79395. if (!bufferView) {
  79396. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  79397. }
  79398. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  79399. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  79400. if (numComponents === 0) {
  79401. throw new Error(context + ": Invalid type " + accessor.type);
  79402. }
  79403. var data;
  79404. var byteOffset = accessor.byteOffset || 0;
  79405. var byteStride = bufferView.byteStride;
  79406. try {
  79407. switch (accessor.componentType) {
  79408. case GLTF2.EComponentType.BYTE: {
  79409. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79410. break;
  79411. }
  79412. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79413. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79414. break;
  79415. }
  79416. case GLTF2.EComponentType.SHORT: {
  79417. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79418. break;
  79419. }
  79420. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79421. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79422. break;
  79423. }
  79424. case GLTF2.EComponentType.UNSIGNED_INT: {
  79425. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79426. break;
  79427. }
  79428. case GLTF2.EComponentType.FLOAT: {
  79429. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79430. break;
  79431. }
  79432. default: {
  79433. throw new Error(context + ": Invalid component type " + accessor.componentType);
  79434. }
  79435. }
  79436. }
  79437. catch (e) {
  79438. throw new Error(context + ": " + e);
  79439. }
  79440. onSuccess(data);
  79441. });
  79442. };
  79443. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  79444. byteOffset += data.byteOffset;
  79445. var targetLength = count * numComponents;
  79446. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  79447. return new typedArray(data.buffer, byteOffset, targetLength);
  79448. }
  79449. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  79450. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  79451. var targetBuffer = new typedArray(targetLength);
  79452. var sourceIndex = 0;
  79453. var targetIndex = 0;
  79454. while (targetIndex < targetLength) {
  79455. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  79456. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  79457. targetIndex++;
  79458. }
  79459. sourceIndex += elementStride;
  79460. }
  79461. return targetBuffer;
  79462. };
  79463. GLTFLoader.prototype._addPendingData = function (data) {
  79464. if (!this._renderReady) {
  79465. this._renderPendingCount++;
  79466. }
  79467. this._addLoaderPendingData(data);
  79468. };
  79469. GLTFLoader.prototype._removePendingData = function (data) {
  79470. if (!this._renderReady) {
  79471. if (--this._renderPendingCount === 0) {
  79472. this._renderReady = true;
  79473. this._onRenderReady();
  79474. }
  79475. }
  79476. this._removeLoaderPendingData(data);
  79477. };
  79478. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  79479. this._loaderPendingCount++;
  79480. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79481. var tracker = _a[_i];
  79482. tracker._addPendingData(data);
  79483. }
  79484. };
  79485. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  79486. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79487. var tracker = _a[_i];
  79488. tracker._removePendingData(data);
  79489. }
  79490. if (--this._loaderPendingCount === 0) {
  79491. this._onComplete();
  79492. }
  79493. };
  79494. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  79495. var _this = this;
  79496. var tracker = new GLTFLoaderTracker(function () {
  79497. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  79498. onComplete();
  79499. });
  79500. this._loaderTrackers.push(tracker);
  79501. this._addLoaderPendingData(tracker);
  79502. action();
  79503. this._removeLoaderPendingData(tracker);
  79504. };
  79505. GLTFLoader.prototype._getDefaultMaterial = function () {
  79506. if (!this._defaultMaterial) {
  79507. var id = "__gltf_default";
  79508. var material = this._babylonScene.getMaterialByName(id);
  79509. if (!material) {
  79510. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  79511. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79512. material.metallic = 1;
  79513. material.roughness = 1;
  79514. }
  79515. this._defaultMaterial = material;
  79516. }
  79517. return this._defaultMaterial;
  79518. };
  79519. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  79520. var babylonMaterial = material.babylonMaterial;
  79521. // Ensure metallic workflow
  79522. babylonMaterial.metallic = 1;
  79523. babylonMaterial.roughness = 1;
  79524. var properties = material.pbrMetallicRoughness;
  79525. if (!properties) {
  79526. return;
  79527. }
  79528. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  79529. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  79530. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  79531. if (properties.baseColorTexture) {
  79532. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  79533. if (!texture) {
  79534. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  79535. }
  79536. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  79537. }
  79538. if (properties.metallicRoughnessTexture) {
  79539. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  79540. if (!texture) {
  79541. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  79542. }
  79543. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  79544. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  79545. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  79546. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  79547. }
  79548. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  79549. };
  79550. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  79551. if (material.babylonMaterial) {
  79552. assign(material.babylonMaterial, false);
  79553. return;
  79554. }
  79555. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  79556. return;
  79557. }
  79558. this._createPbrMaterial(material);
  79559. this._loadMaterialBaseProperties(context, material);
  79560. this._loadMaterialMetallicRoughnessProperties(context, material);
  79561. assign(material.babylonMaterial, true);
  79562. };
  79563. GLTFLoader.prototype._createPbrMaterial = function (material) {
  79564. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  79565. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79566. material.babylonMaterial = babylonMaterial;
  79567. };
  79568. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  79569. var babylonMaterial = material.babylonMaterial;
  79570. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  79571. if (material.doubleSided) {
  79572. babylonMaterial.backFaceCulling = false;
  79573. babylonMaterial.twoSidedLighting = true;
  79574. }
  79575. if (material.normalTexture) {
  79576. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  79577. if (!texture) {
  79578. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  79579. }
  79580. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  79581. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  79582. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  79583. if (material.normalTexture.scale != null) {
  79584. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  79585. }
  79586. }
  79587. if (material.occlusionTexture) {
  79588. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  79589. if (!texture) {
  79590. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  79591. }
  79592. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  79593. babylonMaterial.useAmbientInGrayScale = true;
  79594. if (material.occlusionTexture.strength != null) {
  79595. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  79596. }
  79597. }
  79598. if (material.emissiveTexture) {
  79599. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  79600. if (!texture) {
  79601. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  79602. }
  79603. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  79604. }
  79605. };
  79606. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  79607. var babylonMaterial = material.babylonMaterial;
  79608. var alphaMode = material.alphaMode || "OPAQUE";
  79609. switch (alphaMode) {
  79610. case "OPAQUE": {
  79611. // default is opaque
  79612. break;
  79613. }
  79614. case "MASK": {
  79615. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  79616. if (colorFactor) {
  79617. if (colorFactor[3] == 0) {
  79618. babylonMaterial.alphaCutOff = 1;
  79619. }
  79620. else {
  79621. babylonMaterial.alphaCutOff /= colorFactor[3];
  79622. }
  79623. }
  79624. if (babylonMaterial.albedoTexture) {
  79625. babylonMaterial.albedoTexture.hasAlpha = true;
  79626. }
  79627. break;
  79628. }
  79629. case "BLEND": {
  79630. if (colorFactor) {
  79631. babylonMaterial.alpha = colorFactor[3];
  79632. }
  79633. if (babylonMaterial.albedoTexture) {
  79634. babylonMaterial.albedoTexture.hasAlpha = true;
  79635. babylonMaterial.useAlphaFromAlbedoTexture = true;
  79636. }
  79637. break;
  79638. }
  79639. default: {
  79640. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  79641. }
  79642. }
  79643. };
  79644. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  79645. var _this = this;
  79646. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  79647. if (!sampler) {
  79648. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  79649. }
  79650. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79651. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79652. this._addPendingData(texture);
  79653. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79654. _this._tryCatchOnError(function () {
  79655. _this._removePendingData(texture);
  79656. });
  79657. }, function (message) {
  79658. _this._tryCatchOnError(function () {
  79659. throw new Error(context + ": " + message);
  79660. });
  79661. });
  79662. if (texture.url) {
  79663. babylonTexture.updateURL(texture.url);
  79664. }
  79665. else if (texture.dataReadyObservable) {
  79666. texture.dataReadyObservable.add(function (texture) {
  79667. babylonTexture.updateURL(texture.url);
  79668. });
  79669. }
  79670. else {
  79671. texture.dataReadyObservable = new BABYLON.Observable();
  79672. texture.dataReadyObservable.add(function (texture) {
  79673. babylonTexture.updateURL(texture.url);
  79674. });
  79675. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  79676. if (!image_1) {
  79677. throw new Error(context + ": Failed to find source " + texture.source);
  79678. }
  79679. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79680. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79681. texture.dataReadyObservable.notifyObservers(texture);
  79682. texture.dataReadyObservable = undefined;
  79683. });
  79684. }
  79685. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79686. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  79687. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  79688. babylonTexture.name = texture.name || "texture" + texture.index;
  79689. if (this._parent.onTextureLoaded) {
  79690. this._parent.onTextureLoaded(babylonTexture);
  79691. }
  79692. return babylonTexture;
  79693. };
  79694. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79695. if (image.uri) {
  79696. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79697. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79698. }
  79699. else {
  79700. this._loadUri(context, image.uri, onSuccess);
  79701. }
  79702. }
  79703. else {
  79704. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  79705. if (!bufferView) {
  79706. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79707. }
  79708. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79709. }
  79710. };
  79711. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79712. var _this = this;
  79713. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79714. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79715. }
  79716. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79717. _this._tryCatchOnError(function () {
  79718. onSuccess(new Uint8Array(data));
  79719. });
  79720. }, function (event) {
  79721. _this._tryCatchOnError(function () {
  79722. _this._onProgress(event);
  79723. });
  79724. }, this._babylonScene.database, true, function (request) {
  79725. _this._tryCatchOnError(function () {
  79726. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79727. });
  79728. });
  79729. if (request) {
  79730. this._requests.push(request);
  79731. }
  79732. };
  79733. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79734. if (this._disposed) {
  79735. return;
  79736. }
  79737. try {
  79738. handler();
  79739. }
  79740. catch (e) {
  79741. BABYLON.Tools.Error("glTF Loader: " + e.message);
  79742. if (this._errorCallback) {
  79743. this._errorCallback(e.message);
  79744. }
  79745. this.dispose();
  79746. }
  79747. };
  79748. GLTFLoader._AssignIndices = function (array) {
  79749. if (array) {
  79750. for (var index = 0; index < array.length; index++) {
  79751. array[index].index = index;
  79752. }
  79753. }
  79754. };
  79755. GLTFLoader._GetProperty = function (array, index) {
  79756. if (!array || index == undefined || !array[index]) {
  79757. return null;
  79758. }
  79759. return array[index];
  79760. };
  79761. GLTFLoader._GetTextureWrapMode = function (mode) {
  79762. // Set defaults if undefined
  79763. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79764. switch (mode) {
  79765. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79766. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79767. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79768. default:
  79769. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79770. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79771. }
  79772. };
  79773. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  79774. // Set defaults if undefined
  79775. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79776. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79777. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79778. switch (minFilter) {
  79779. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79780. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79781. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79782. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79783. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79784. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79785. default:
  79786. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79787. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79788. }
  79789. }
  79790. else {
  79791. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79792. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79793. }
  79794. switch (minFilter) {
  79795. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79796. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79797. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79798. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79799. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79800. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79801. default:
  79802. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79803. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79804. }
  79805. }
  79806. };
  79807. GLTFLoader._GetNumComponents = function (type) {
  79808. switch (type) {
  79809. case "SCALAR": return 1;
  79810. case "VEC2": return 2;
  79811. case "VEC3": return 3;
  79812. case "VEC4": return 4;
  79813. case "MAT2": return 4;
  79814. case "MAT3": return 9;
  79815. case "MAT4": return 16;
  79816. }
  79817. return 0;
  79818. };
  79819. GLTFLoader.Extensions = {};
  79820. return GLTFLoader;
  79821. }());
  79822. GLTF2.GLTFLoader = GLTFLoader;
  79823. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  79824. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79825. })(BABYLON || (BABYLON = {}));
  79826. //# sourceMappingURL=babylon.glTFLoader.js.map
  79827. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79828. var BABYLON;
  79829. (function (BABYLON) {
  79830. var GLTF2;
  79831. (function (GLTF2) {
  79832. /**
  79833. * Utils functions for GLTF
  79834. */
  79835. var GLTFUtils = /** @class */ (function () {
  79836. function GLTFUtils() {
  79837. }
  79838. /**
  79839. * If the uri is a base64 string
  79840. * @param uri: the uri to test
  79841. */
  79842. GLTFUtils.IsBase64 = function (uri) {
  79843. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79844. };
  79845. /**
  79846. * Decode the base64 uri
  79847. * @param uri: the uri to decode
  79848. */
  79849. GLTFUtils.DecodeBase64 = function (uri) {
  79850. var decodedString = atob(uri.split(",")[1]);
  79851. var bufferLength = decodedString.length;
  79852. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79853. for (var i = 0; i < bufferLength; i++) {
  79854. bufferView[i] = decodedString.charCodeAt(i);
  79855. }
  79856. return bufferView.buffer;
  79857. };
  79858. GLTFUtils.ValidateUri = function (uri) {
  79859. return (uri.indexOf("..") === -1);
  79860. };
  79861. return GLTFUtils;
  79862. }());
  79863. GLTF2.GLTFUtils = GLTFUtils;
  79864. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79865. })(BABYLON || (BABYLON = {}));
  79866. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79867. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79868. var BABYLON;
  79869. (function (BABYLON) {
  79870. var GLTF2;
  79871. (function (GLTF2) {
  79872. var GLTFLoaderExtension = /** @class */ (function () {
  79873. function GLTFLoaderExtension() {
  79874. this.enabled = true;
  79875. }
  79876. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  79877. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  79878. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  79879. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  79880. var _this = this;
  79881. if (!property.extensions) {
  79882. return false;
  79883. }
  79884. var extension = property.extensions[this.name];
  79885. if (!extension) {
  79886. return false;
  79887. }
  79888. // Clear out the extension before executing the action to avoid recursing into the same property.
  79889. property.extensions[this.name] = undefined;
  79890. action(context + "extensions/" + this.name, extension, function () {
  79891. // Restore the extension after completing the action.
  79892. property.extensions[_this.name] = extension;
  79893. });
  79894. return true;
  79895. };
  79896. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  79897. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  79898. };
  79899. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  79900. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  79901. };
  79902. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  79903. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  79904. };
  79905. GLTFLoaderExtension._ApplyExtensions = function (action) {
  79906. var extensions = GLTFLoaderExtension._Extensions;
  79907. if (!extensions) {
  79908. return false;
  79909. }
  79910. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  79911. var extension = extensions_1[_i];
  79912. if (extension.enabled && action(extension)) {
  79913. return true;
  79914. }
  79915. }
  79916. return false;
  79917. };
  79918. //
  79919. // Utilities
  79920. //
  79921. GLTFLoaderExtension._Extensions = [];
  79922. return GLTFLoaderExtension;
  79923. }());
  79924. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  79925. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79926. })(BABYLON || (BABYLON = {}));
  79927. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79928. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79929. var BABYLON;
  79930. (function (BABYLON) {
  79931. var GLTF2;
  79932. (function (GLTF2) {
  79933. var Extensions;
  79934. (function (Extensions) {
  79935. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  79936. var MSFTLOD = /** @class */ (function (_super) {
  79937. __extends(MSFTLOD, _super);
  79938. function MSFTLOD() {
  79939. return _super !== null && _super.apply(this, arguments) || this;
  79940. }
  79941. Object.defineProperty(MSFTLOD.prototype, "name", {
  79942. get: function () {
  79943. return "MSFT_lod";
  79944. },
  79945. enumerable: true,
  79946. configurable: true
  79947. });
  79948. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  79949. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79950. for (var i = extension.ids.length - 1; i >= 0; i--) {
  79951. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  79952. if (!lodNode) {
  79953. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  79954. }
  79955. loader._traverseNode(context, lodNode, action, parentNode);
  79956. }
  79957. loader._traverseNode(context, node, action, parentNode);
  79958. onComplete();
  79959. });
  79960. };
  79961. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  79962. var _this = this;
  79963. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79964. var nodes = [node];
  79965. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  79966. var index = _a[_i];
  79967. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  79968. if (!lodNode) {
  79969. throw new Error(context + ": Failed to find node " + index);
  79970. }
  79971. nodes.push(lodNode);
  79972. }
  79973. loader._addLoaderPendingData(node);
  79974. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  79975. loader._removeLoaderPendingData(node);
  79976. onComplete();
  79977. });
  79978. });
  79979. };
  79980. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  79981. var _this = this;
  79982. loader._whenAction(function () {
  79983. loader._loadNode(context, nodes[index]);
  79984. }, function () {
  79985. if (index !== nodes.length - 1) {
  79986. var previousNode = nodes[index + 1];
  79987. previousNode.babylonMesh.setEnabled(false);
  79988. }
  79989. if (index === 0) {
  79990. onComplete();
  79991. return;
  79992. }
  79993. setTimeout(function () {
  79994. loader._tryCatchOnError(function () {
  79995. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  79996. });
  79997. }, MSFTLOD.MinimalLODDelay);
  79998. });
  79999. };
  80000. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  80001. var _this = this;
  80002. return this._loadExtension(context, material, function (context, extension, onComplete) {
  80003. var materials = [material];
  80004. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  80005. var index = _a[_i];
  80006. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  80007. if (!lodMaterial) {
  80008. throw new Error(context + ": Failed to find material " + index);
  80009. }
  80010. materials.push(lodMaterial);
  80011. }
  80012. loader._addLoaderPendingData(material);
  80013. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  80014. loader._removeLoaderPendingData(material);
  80015. onComplete();
  80016. });
  80017. });
  80018. };
  80019. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  80020. var _this = this;
  80021. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  80022. assign(babylonMaterial, isNew);
  80023. if (index === 0) {
  80024. onComplete();
  80025. return;
  80026. }
  80027. // Load the next LOD when the loader is ready to render and
  80028. // all active material textures of the current LOD are loaded.
  80029. loader._executeWhenRenderReady(function () {
  80030. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  80031. setTimeout(function () {
  80032. loader._tryCatchOnError(function () {
  80033. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  80034. });
  80035. }, MSFTLOD.MinimalLODDelay);
  80036. });
  80037. });
  80038. });
  80039. };
  80040. /**
  80041. * Specify the minimal delay between LODs in ms (default = 250)
  80042. */
  80043. MSFTLOD.MinimalLODDelay = 250;
  80044. return MSFTLOD;
  80045. }(GLTF2.GLTFLoaderExtension));
  80046. Extensions.MSFTLOD = MSFTLOD;
  80047. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  80048. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80049. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80050. })(BABYLON || (BABYLON = {}));
  80051. //# sourceMappingURL=MSFT_lod.js.map
  80052. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  80053. var BABYLON;
  80054. (function (BABYLON) {
  80055. var GLTF2;
  80056. (function (GLTF2) {
  80057. var Extensions;
  80058. (function (Extensions) {
  80059. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  80060. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  80061. function KHRMaterialsPbrSpecularGlossiness() {
  80062. return _super !== null && _super.apply(this, arguments) || this;
  80063. }
  80064. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  80065. get: function () {
  80066. return "KHR_materials_pbrSpecularGlossiness";
  80067. },
  80068. enumerable: true,
  80069. configurable: true
  80070. });
  80071. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  80072. var _this = this;
  80073. return this._loadExtension(context, material, function (context, extension, onComplete) {
  80074. loader._createPbrMaterial(material);
  80075. loader._loadMaterialBaseProperties(context, material);
  80076. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  80077. assign(material.babylonMaterial, true);
  80078. });
  80079. };
  80080. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  80081. var babylonMaterial = material.babylonMaterial;
  80082. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  80083. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  80084. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  80085. if (properties.diffuseTexture) {
  80086. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  80087. if (!texture) {
  80088. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  80089. }
  80090. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  80091. }
  80092. if (properties.specularGlossinessTexture) {
  80093. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  80094. if (!texture) {
  80095. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  80096. }
  80097. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  80098. babylonMaterial.reflectivityTexture.hasAlpha = true;
  80099. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  80100. }
  80101. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  80102. };
  80103. return KHRMaterialsPbrSpecularGlossiness;
  80104. }(GLTF2.GLTFLoaderExtension));
  80105. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  80106. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  80107. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80108. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80109. })(BABYLON || (BABYLON = {}));
  80110. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  80111. (function universalModuleDefinition(root, factory) {
  80112. if (root && root["BABYLON"]) {
  80113. return;
  80114. }
  80115. if(typeof exports === 'object' && typeof module === 'object')
  80116. module.exports = factory();
  80117. else if(typeof define === 'function' && define.amd)
  80118. define([], factory);
  80119. else if(typeof exports === 'object')
  80120. exports["BABYLON"] = factory();
  80121. else {
  80122. root["BABYLON"] = factory();
  80123. }
  80124. })(this, function() {
  80125. return BABYLON;
  80126. });